forked from electronicarts/CnC_Generals_Zero_Hour
-
Notifications
You must be signed in to change notification settings - Fork 182
Expand file tree
/
Copy pathBaseHeightMap.cpp
More file actions
3010 lines (2632 loc) · 99.4 KB
/
BaseHeightMap.cpp
File metadata and controls
3010 lines (2632 loc) · 99.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
/*
** 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) 2001-2003 Electronic Arts Inc. //
// //
////////////////////////////////////////////////////////////////////////////////
// FILE: Heightmap.cpp ////////////////////////////////////////////////
//-----------------------------------------------------------------------------
//
// Westwood Studios Pacific.
//
// Confidential Information
// Copyright (C) 2001 - All Rights Reserved
//
//-----------------------------------------------------------------------------
//
// Project: RTS3
//
// File name: Heightmap.cpp
//
// Created: Mark W., John Ahlquist, April/May 2001
//
// Desc: Draw the terrain and scorchmarks in a scene.
//
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Includes
//-----------------------------------------------------------------------------
#include <stdlib.h>
#include <assetmgr.h>
#include <texture.h>
#include <tri.h>
#include <colmath.h>
#include <coltest.h>
#include <rinfo.h>
#include <camera.h>
#include <d3dx8core.h>
#include "Common/GlobalData.h"
#include "Common/PerfTimer.h"
#include "Common/Xfer.h"
#include "GameClient/TerrainVisual.h"
#include "GameClient/View.h"
#include "GameClient/Water.h"
#include "GameLogic/AIPathfind.h"
#include "GameLogic/TerrainLogic.h"
#include "W3DDevice/GameClient/TerrainTex.h"
#include "W3DDevice/GameClient/W3DDynamicLight.h"
#include "W3DDevice/GameClient/W3DScene.h"
#include "W3DDevice/GameClient/W3DTerrainTracks.h"
#include "W3DDevice/GameClient/W3DBibBuffer.h"
#include "W3DDevice/GameClient/W3DPropBuffer.h"
#include "W3DDevice/GameClient/W3DTreeBuffer.h"
#include "W3DDevice/GameClient/W3DRoadBuffer.h"
#include "W3DDevice/GameClient/W3DBridgeBuffer.h"
#include "W3DDevice/GameClient/W3DWaypointBuffer.h"
#include "W3DDevice/GameClient/W3DCustomEdging.h"
#include "W3DDevice/GameClient/WorldHeightMap.h"
#include "W3DDevice/GameClient/W3DShaderManager.h"
#include "W3DDevice/GameClient/W3DShadow.h"
#include "W3DDevice/GameClient/W3DWater.h"
#include "W3DDevice/GameClient/W3DShroud.h"
#include "WW3D2/dx8wrapper.h"
#include "WW3D2/light.h"
#include "WW3D2/scene.h"
#include "W3DDevice/GameClient/W3DPoly.h"
#include "W3DDevice/GameClient/W3DCustomScene.h"
#include "Common/UnitTimings.h" //Contains the DO_UNIT_TIMINGS define jba.
#include "W3DDevice/GameClient/BaseHeightMap.h"
#include "W3DDevice/GameClient/HeightMap.h"
#include "W3DDevice/GameClient/FlatHeightMap.h"
#include "W3DDevice/GameClient/W3DSmudge.h"
#include "W3DDevice/GameClient/W3DSnow.h"
extern FlatHeightMapRenderObjClass *TheFlatHeightMap;
extern HeightMapRenderObjClass *TheHeightMap;
//-----------------------------------------------------------------------------
// Private Data
//-----------------------------------------------------------------------------
#define SC_DETAIL_BLEND ( SHADE_CNST(ShaderClass::PASS_LEQUAL, ShaderClass::DEPTH_WRITE_ENABLE, ShaderClass::COLOR_WRITE_ENABLE, ShaderClass::SRCBLEND_ONE, \
ShaderClass::DSTBLEND_ZERO, ShaderClass::FOG_DISABLE, ShaderClass::GRADIENT_MODULATE, ShaderClass::SECONDARY_GRADIENT_DISABLE, ShaderClass::TEXTURING_ENABLE, \
ShaderClass::ALPHATEST_DISABLE, ShaderClass::CULL_MODE_ENABLE, ShaderClass::DETAILCOLOR_SCALE, ShaderClass::DETAILALPHA_DISABLE) )
static ShaderClass detailOpaqueShader(SC_DETAIL_BLEND);
//-----------------------------------------------------------------------------
// Global Functions & Data
//-----------------------------------------------------------------------------
/// The one-of for the terrain rendering object.
BaseHeightMapRenderObjClass *TheTerrainRenderObject=nullptr;
/** Entry point so that trees can be drawn at the appropriate point in the rendering pipe for
transparent objects. */
void DoTrees(RenderInfoClass & rinfo)
{
if (TheTerrainRenderObject) {
TheTerrainRenderObject->renderTrees(&rinfo.Camera);
}
}
void oversizeTheTerrain(Int amount)
{
if (TheTerrainRenderObject)
{
TheTerrainRenderObject->oversizeTerrain(amount);
}
}
#define DEFAULT_MAX_BATCH_SHORELINE_TILES 512 //maximum number of terrain tiles rendered per call (must fit in one VB)
#define DEFAULT_MAX_MAP_SHORELINE_TILES 4096 //default size of array allocated to hold all map shoreline tiles.
#define ADJUST_FROM_INDEX_TO_REAL(k) ((k-m_map->getBorderSizeInline())*MAP_XY_FACTOR)
inline Int IABS(Int x) { if (x>=0) return x; return -x;};
//-----------------------------------------------------------------------------
// Private Functions
//-----------------------------------------------------------------------------
//=============================================================================
// BaseHeightMapRenderObjClass::freeMapResources
//=============================================================================
/** Frees the w3d resources used to draw the terrain. */
//=============================================================================
Int BaseHeightMapRenderObjClass::freeMapResources()
{
#ifdef DO_SCORCH
freeScorchBuffers();
#endif
REF_PTR_RELEASE(m_vertexMaterialClass);
REF_PTR_RELEASE(m_stageZeroTexture);
REF_PTR_RELEASE(m_stageOneTexture);
REF_PTR_RELEASE(m_stageTwoTexture);
REF_PTR_RELEASE(m_stageThreeTexture);
REF_PTR_RELEASE(m_destAlphaTexture);
REF_PTR_RELEASE(m_map);
return 0;
}
#ifdef DO_SCORCH
//=============================================================================
// BaseHeightMapRenderObjClass::drawScorches
//=============================================================================
/** Draws the scorch marks. */
//=============================================================================
void BaseHeightMapRenderObjClass::drawScorches()
{
updateScorches();
if (m_curNumScorchIndices == 0) {
return;
}
DX8Wrapper::Set_Index_Buffer(m_indexScorch,0);
DX8Wrapper::Set_Vertex_Buffer(m_vertexScorch);
DX8Wrapper::Set_Shader(ShaderClass::_PresetAlphaShader);
DX8Wrapper::Set_Texture(0,m_scorchTexture);
if (Is_Hidden() == 0) {
DX8Wrapper::Draw_Triangles( 0,m_curNumScorchIndices/3, 0, m_curNumScorchVertices);
}
}
#endif
//-----------------------------------------------------------------------------
// Public Functions
//-----------------------------------------------------------------------------
//=============================================================================
// BaseHeightMapRenderObjClass::~BaseHeightMapRenderObjClass
//=============================================================================
/** Destructor. Releases w3d assets. */
//=============================================================================
BaseHeightMapRenderObjClass::~BaseHeightMapRenderObjClass()
{
freeMapResources();
delete m_treeBuffer;
m_treeBuffer = nullptr;
delete m_propBuffer;
m_propBuffer = nullptr;
delete m_bibBuffer;
m_bibBuffer = nullptr;
#ifdef DO_ROADS
delete m_roadBuffer;
m_roadBuffer = nullptr;
#endif
delete m_bridgeBuffer;
m_bridgeBuffer = nullptr;
delete m_waypointBuffer;
m_waypointBuffer = nullptr;
delete m_shroud;
m_shroud = nullptr;
delete [] m_shoreLineTilePositions;
m_shoreLineTilePositions = nullptr;
delete [] m_shoreLineSortInfos;
m_shoreLineSortInfos = nullptr;
}
//=============================================================================
// BaseHeightMapRenderObjClass::BaseHeightMapRenderObjClass
//=============================================================================
/** Constructor. Mostly nulls out the member variables. */
//=============================================================================
BaseHeightMapRenderObjClass::BaseHeightMapRenderObjClass()
{
m_x=0;
m_y=0;
m_needFullUpdate = false;
m_showImpassableAreas = false;
m_updating = false;
//Set height to the maximum value that can be stored.
//We should refine this with actual value.
m_maxHeight=(pow(256.0, sizeof(HeightSampleType))-1.0)*MAP_HEIGHT_SCALE;
m_minHeight=0;
m_shoreLineTilePositions=nullptr;
m_numShoreLineTiles=0;
m_shoreLineSortInfos=nullptr;
m_shoreLineSortInfosSize=0;
m_shoreLineSortInfosXMajor=TRUE;
m_shoreLineTileSortMaxCoordinate=0;
m_shoreLineTileSortMinCoordinate=0;
m_numVisibleShoreLineTiles=0;
m_shoreLineTilePositionsSize=0;
m_currentMinWaterOpacity = -1.0f;
m_vertexMaterialClass=nullptr;
m_stageZeroTexture=nullptr;
m_stageOneTexture=nullptr;
m_stageTwoTexture=nullptr;
m_stageThreeTexture=nullptr;
m_destAlphaTexture=nullptr;
m_map=nullptr;
m_depthFade.X = 0.0f;
m_depthFade.Y = 0.0f;
m_depthFade.Z = 0.0f;
m_useDepthFade = false;
m_disableTextures = false;
TheTerrainRenderObject = this;
m_treeBuffer = nullptr;
m_propBuffer = nullptr;
m_bibBuffer = nullptr;
m_bridgeBuffer = nullptr;
m_waypointBuffer = nullptr;
#ifdef DO_ROADS
m_roadBuffer = nullptr;
#endif
#ifdef DO_SCORCH
m_vertexScorch = nullptr;
m_indexScorch = nullptr;
m_scorchTexture = nullptr;
clearAllScorches();
m_shroud = nullptr;
#endif
m_bridgeBuffer = NEW W3DBridgeBuffer;
if (TheGlobalData->m_headless)
return;
m_treeBuffer = NEW W3DTreeBuffer;
m_propBuffer = NEW W3DPropBuffer;
m_bibBuffer = NEW W3DBibBuffer;
m_curImpassableSlope = 45.0f; // default to 45 degrees.
m_waypointBuffer = NEW W3DWaypointBuffer;
#ifdef DO_ROADS
m_roadBuffer = NEW W3DRoadBuffer;
#endif
#if ENABLE_CONFIGURABLE_SHROUD
if (TheGlobalData->m_shroudOn)
m_shroud = NEW W3DShroud;
#else
m_shroud = NEW W3DShroud;
#endif
DX8Wrapper::SetCleanupHook(this);
}
void BaseHeightMapRenderObjClass::setTextureLOD(Int lod)
{
if (m_treeBuffer)
m_treeBuffer->setTextureLOD(lod);
if (m_map)
m_map->setTextureLOD(lod);
}
//=============================================================================
// BaseHeightMapRenderObjClass::adjustTerrainLOD
//=============================================================================
/** Adjust the terrain Level Of Detail. If adj > 0 , increases LOD 1 step, if
adj < 0 decreases it one step, if adj==0, then just sets up for the current LOD */
//=============================================================================
void BaseHeightMapRenderObjClass::adjustTerrainLOD(Int adj)
{
if (adj>0 && TheGlobalData->m_terrainLOD<TERRAIN_LOD_MAX) TheWritableGlobalData->m_terrainLOD=(TerrainLOD)(TheGlobalData->m_terrainLOD+1);
if (adj<0 && TheGlobalData->m_terrainLOD>TERRAIN_LOD_MIN) TheWritableGlobalData->m_terrainLOD=(TerrainLOD)(TheGlobalData->m_terrainLOD-1);
if (TheGlobalData->m_terrainLOD ==TERRAIN_LOD_AUTOMATIC) {
TheWritableGlobalData->m_terrainLOD=TERRAIN_LOD_MAX;
}
if (m_map==nullptr) return;
if (m_shroud)
m_shroud->reset(); //need reset here since initHeightData will load new shroud.
BaseHeightMapRenderObjClass *newROBJ = nullptr;
if (TheGlobalData->m_terrainLOD==7) {
newROBJ = TheHeightMap;
if (newROBJ==nullptr) {
newROBJ = NEW_REF( HeightMapRenderObjClass, () );
}
} else {
newROBJ = TheFlatHeightMap;
if (newROBJ==nullptr) {
newROBJ = NEW_REF( FlatHeightMapRenderObjClass, () );
}
}
if (TheGlobalData->m_terrainLOD == 5)
newROBJ = nullptr;
RTS3DScene *pMyScene = (RTS3DScene *)Scene;
if (pMyScene) {
pMyScene->Remove_Render_Object(this);
pMyScene->Unregister(this, SceneClass::ON_FRAME_UPDATE);
// add our terrain render object to the scene
if (newROBJ) {
pMyScene->Add_Render_Object( newROBJ );
pMyScene->Register(newROBJ,SceneClass::ON_FRAME_UPDATE);
}
}
if (newROBJ) {
// apply the heightmap to the terrain render object
newROBJ->initHeightData( m_map->getDrawWidth(),
m_map->getDrawHeight(),
m_map,
nullptr);
TheTerrainRenderObject = newROBJ;
newROBJ->staticLightingChanged();
newROBJ->m_roadBuffer->loadRoads();
}
if (TheTacticalView) {
TheTacticalView->forceRedraw();
}
}
//=============================================================================
// BaseHeightMapRenderObjClass::ReleaseResources
//=============================================================================
/** Releases all w3d assets, to prepare for Reset device call. */
//=============================================================================
void BaseHeightMapRenderObjClass::ReleaseResources()
{
if (m_treeBuffer) {
m_treeBuffer->freeTreeBuffers();
}
if (m_bibBuffer) {
m_bibBuffer->freeBibBuffers();
}
if (m_bridgeBuffer) {
m_bridgeBuffer->freeBridgeBuffers();
}
if( m_waypointBuffer )
{
m_waypointBuffer->freeWaypointBuffers();
}
// We need to save the map.
WorldHeightMap *pMap=nullptr;
REF_PTR_SET(pMap, m_map);
freeMapResources();
m_map = pMap; // ref_ptr_set has already incremented the ref count.
if (TheWaterRenderObj)
TheWaterRenderObj->ReleaseResources();
if (TheTerrainTracksRenderObjClassSystem)
TheTerrainTracksRenderObjClassSystem->ReleaseResources();
if (TheW3DShadowManager)
TheW3DShadowManager->ReleaseResources();
if (m_shroud)
{ m_shroud->reset();
m_shroud->ReleaseResources();
}
if (TheSmudgeManager)
TheSmudgeManager->ReleaseResources();
if (TheSnowManager)
((W3DSnowManager *)TheSnowManager)->ReleaseResources();
//Release any resources that may be used by custom pixel/vertex shaders
W3DShaderManager::shutdown();
#ifdef DO_ROADS
if (m_roadBuffer) {
m_roadBuffer->freeRoadBuffers();
}
#endif
}
//=============================================================================
// BaseHeightMapRenderObjClass::ReAcquireResources
//=============================================================================
/** Reallocates all W3D assets after a reset.. */
//=============================================================================
void BaseHeightMapRenderObjClass::ReAcquireResources()
{
W3DShaderManager::init(); //reaquire resources which may be needed by custom shaders
if (TheWaterRenderObj)
TheWaterRenderObj->ReAcquireResources();
if (TheTerrainTracksRenderObjClassSystem)
TheTerrainTracksRenderObjClassSystem->ReAcquireResources();
if (TheW3DShadowManager)
TheW3DShadowManager->ReAcquireResources();
if (m_shroud)
m_shroud->ReAcquireResources();
if (m_map)
{
this->initHeightData(m_x,m_y,m_map, nullptr);
// Tell lights to update next time through.
m_needFullUpdate = true;
}
if (m_treeBuffer) {
m_treeBuffer->allocateTreeBuffers();
}
if (m_bibBuffer) {
m_bibBuffer->allocateBibBuffers();
}
if (m_bridgeBuffer) {
m_bridgeBuffer->allocateBridgeBuffers();
}
if (TheSmudgeManager)
TheSmudgeManager->ReAcquireResources();
if (TheSnowManager)
((W3DSnowManager *)TheSnowManager)->ReAcquireResources();
//Waypoint buffers are done dynamically. One line, one node (just rendered multiple times accessing other data).
//Internally creates it if needed.
#ifdef DO_ROADS
if (m_roadBuffer) {
m_roadBuffer->allocateRoadBuffers();
m_roadBuffer->loadRoads();
}
#endif
if (TheTacticalView) {
TheTacticalView->forceRedraw(); //force map to update itself for the current camera position.
}
}
//=============================================================================
// BaseHeightMapRenderObjClass::doTheLight
//=============================================================================
/** Calculates the diffuse lighting for a vertex in the terrain, taking all of the
static lights into account as well. It is possible to just use the normal in the
vertex and let D3D do the lighting, but it is slower to render, and can only
handle 4 lights at this point. */
//=============================================================================
void BaseHeightMapRenderObjClass::doTheLight(VERTEX_FORMAT *vb, const Vector3*light, Vector3*normal, RefRenderObjListIterator *pLightsIterator, UnsignedByte alpha)
{
#ifdef USE_NORMALS
vb->nx = normal->X;
vb->ny = normal->Y;
vb->nz = normal->Z;
#else
Real shadeR, shadeG, shadeB;
Real shade;
shadeR = TheGlobalData->m_terrainAmbient[0].red; //only the first terrain light contributes to ambient
shadeG = TheGlobalData->m_terrainAmbient[0].green;
shadeB = TheGlobalData->m_terrainAmbient[0].blue;
if (pLightsIterator) {
for (pLightsIterator->First(); !pLightsIterator->Is_Done(); pLightsIterator->Next())
{
LightClass *pLight = (LightClass*)pLightsIterator->Peek_Obj();
Vector3 lightDirection(vb->x, vb->y, vb->z);
Real factor = 1.0f;
switch(pLight->Get_Type()) {
case LightClass::POINT:
case LightClass::SPOT: {
Vector3 lightLoc = pLight->Get_Position();
lightDirection -= lightLoc;
double range, midRange;
pLight->Get_Far_Attenuation_Range(midRange, range);
if (vb->x < lightLoc.X-range) continue;
if (vb->x > lightLoc.X+range) continue;
if (vb->y < lightLoc.Y-range) continue;
if (vb->y > lightLoc.Y+range) continue;
Real dist = lightDirection.Length();
if (dist >= range) continue;
if (midRange < 0.1) continue;
#if 1
factor = 1.0f - (dist - midRange) / (range - midRange);
#else
// f = 1.0 / (atten0 + d*atten1 + d*d/atten2);
if (fabs(range-midRange)<1e-5) {
// if the attenuation range is too small assume uniform with cutoff
factor = 1.0;
} else {
factor = 1.0f/(0.1+dist/midRange + 5.0f*dist*dist/(range*range));
}
#endif
factor = WWMath::Clamp(factor,0.0f,1.0f);
}
break;
case LightClass::DIRECTIONAL:
lightDirection = pLight->Get_Transform().Get_Z_Vector();
factor = 1.0;
break;
};
lightDirection.Normalize();
Vector3 lightRay(-lightDirection.X, -lightDirection.Y, -lightDirection.Z);
shade = Vector3::Dot_Product(lightRay, *normal);
shade *= factor;
Vector3 diffuse;
pLight->Get_Diffuse(&diffuse);
Vector3 ambient;
pLight->Get_Ambient(&ambient);
if (shade > 1.0) shade = 1.0;
if(shade < 0.0f) shade = 0.0f;
shadeR += shade*diffuse.X;
shadeG += shade*diffuse.Y;
shadeB += shade*diffuse.Z;
shadeR += factor*ambient.X;
shadeG += factor*ambient.Y;
shadeB += factor*ambient.Z;
}
}
// Add in global diffuse value.
const RGBColor *terrainDiffuse;
for (Int lightIndex=0; lightIndex < TheGlobalData->m_numGlobalLights; lightIndex++)
{
shade = Vector3::Dot_Product(light[lightIndex], *normal);
if (shade > 1.0) shade = 1.0;
if(shade < 0.0f) shade = 0.0f;
terrainDiffuse=&TheGlobalData->m_terrainDiffuse[lightIndex];
shadeR += shade*terrainDiffuse->red;
shadeG += shade*terrainDiffuse->green;
shadeB += shade*terrainDiffuse->blue;
}
if (shadeR > 1.0) shadeR = 1.0;
if(shadeR < 0.0f) shadeR = 0.0f;
if (shadeG > 1.0) shadeG = 1.0;
if(shadeG < 0.0f) shadeG = 0.0f;
if (shadeB > 1.0) shadeB = 1.0;
if(shadeB < 0.0f) shadeB = 0.0f;
if (m_useDepthFade && vb->z <= TheGlobalData->m_waterPositionZ)
{ //height is below water level
//reduce lighting values based on light fall off as it travels through water.
float depthScale = (1.4f - vb->z)/TheGlobalData->m_waterPositionZ;
shadeR *= 1.0f - depthScale * (1.0f-m_depthFade.X);
shadeG *= 1.0f - depthScale * (1.0f-m_depthFade.Y);
shadeB *= 1.0f - depthScale * (1.0f-m_depthFade.Z);
}
shadeR*=255.0f;
shadeG*=255.0f;
shadeB*=255.0f;
vb->diffuse = REAL_TO_INT(shadeB) | (REAL_TO_INT(shadeG) << 8) | (REAL_TO_INT(shadeR) << 16) | ((Int)alpha << 24);
#endif
}
//=============================================================================
// BaseHeightMapRenderObjClass::updateMacroTexture
//=============================================================================
/** Updates the macro noise/lightmap texture (pass 3) */
//=============================================================================
void BaseHeightMapRenderObjClass::updateMacroTexture(AsciiString textureName)
{
m_macroTextureName = textureName;
// Release texture.
REF_PTR_RELEASE(m_stageThreeTexture);
// Reallocate texture.
m_stageThreeTexture=NEW LightMapTerrainTextureClass(m_macroTextureName);
}
//=============================================================================
// BaseHeightMapRenderObjClass::reset
//=============================================================================
/** Updates the macro noise/lightmap texture (pass 3) */
//=============================================================================
void BaseHeightMapRenderObjClass::reset()
{
if (m_treeBuffer) {
m_treeBuffer->clearAllTrees();
}
if (m_propBuffer) {
m_propBuffer->clearAllProps();
}
clearAllScorches();
#ifdef TEST_CUSTOM_EDGING
m_customEdging ->clearAllEdging();
#endif
#ifdef DO_ROADS
if (m_roadBuffer) {
m_roadBuffer->clearAllRoads();
}
#endif
if (m_bridgeBuffer) {
m_bridgeBuffer->clearAllBridges();
}
if (m_bibBuffer) {
m_bibBuffer->clearAllBibs();
}
m_showAsVisibleCliff.clear();
if (m_shroud)
{ m_shroud->reset();
m_shroud->setBorderShroudLevel((W3DShroudLevel)TheGlobalData->m_shroudAlpha); //assume border is always black at start.
}
}
/**@todo: Ray intersection needs to be optimized with some sort of grid-tracing
(ala line drawing). We should also try making the search in a front->back order
relative to the ray so we can early exit as soon as we have a hit.
*
//=============================================================================
// BaseHeightMapRenderObjClass::Cast_Ray
//=============================================================================
/** Return intersection of a ray with the heightmap mesh.
This is a quick version that just checks every polygon inside
a 2D bounding rectangle of the ray projected onto the heightfield plane.
For most of our view-picking cases the ray is almost perpendicular to the
map plane so this is very quick (small bounding box). But it can become slow
for arbitrary rays such as those used in AI visibility checks(2 units on
opposite corners of the map would check every polygon in the map).
*/
//=============================================================================
bool BaseHeightMapRenderObjClass::Cast_Ray(RayCollisionTestClass & raytest)
{
TriClass tri;
Bool hit = false;
Int X,Y;
Vector3 normal,P0,P1,P2,P3;
if (!m_map)
return false; //need valid pointer to heightmap samples
//HeightSampleType *pData = m_map->getDataPtr();
//Clip ray to extents of heightfield
AABoxClass hbox;
LineSegClass lineseg,lineseg2;
CastResultStruct result;
Int StartCellX = 0;
Int EndCellX = 0;
Int StartCellY = 0;
Int EndCellY = 0;
const Int overhang = 2*VERTEX_BUFFER_TILE_LENGTH + m_map->getBorderSizeInline(); // Allow picking past the edge for scrolling & objects.
Vector3 minPt(MAP_XY_FACTOR*(-overhang), MAP_XY_FACTOR*(-overhang), -MAP_XY_FACTOR);
Vector3 maxPt(MAP_XY_FACTOR*(m_map->getXExtent()+overhang),
MAP_XY_FACTOR*(m_map->getYExtent()+overhang), MAP_HEIGHT_SCALE*m_map->getMaxHeightValue()+MAP_XY_FACTOR);
MinMaxAABoxClass mmbox(minPt, maxPt);
hbox.Init(mmbox);
lineseg=raytest.Ray;
//Set initial ray endpoints
P0 = raytest.Ray.Get_P0();
P1 = raytest.Ray.Get_P1();
result.ComputeContactPoint=true;
Int p;
for (p=0; p<3; p++) {
//find intersection point of ray and terrain bounding box
result.Reset();
result.ComputeContactPoint=true;
if (CollisionMath::Collide(lineseg,hbox,&result))
{ //ray intersects terrain or starts inside the terrain.
if (!result.StartBad) //check if start point inside terrain
P0 = result.ContactPoint; //make intersection point the new start of the ray.
//reverse direction of original ray and clip again to extent of
//heightmap
result.Fraction=1.0f; //reset the result
result.StartBad=false;
lineseg2.Set(lineseg.Get_P1(),lineseg.Get_P0()); //reverse line segment
if (CollisionMath::Collide(lineseg2,hbox,&result))
{ if (!result.StartBad) //check if end point inside terrain
P1 = result.ContactPoint; //make intersection point the new end pont of ray
}
} else {
if (p==0) return(false);
break;
}
// Take the 2D bounding box of ray and check heights
// inside this box for intersection.
if (P0.X > P1.X) { //flip start/end points
StartCellX = REAL_TO_INT_FLOOR(P1.X/MAP_XY_FACTOR);
EndCellX = REAL_TO_INT_CEIL(P0.X/MAP_XY_FACTOR);
} else {
StartCellX = REAL_TO_INT_FLOOR(P0.X/MAP_XY_FACTOR);
EndCellX = REAL_TO_INT_CEIL(P1.X/MAP_XY_FACTOR);
}
if (P0.Y > P1.Y) { //flip start/end points
StartCellY = REAL_TO_INT_FLOOR(P1.Y/MAP_XY_FACTOR);
EndCellY = REAL_TO_INT_CEIL(P0.Y/MAP_XY_FACTOR);
} else {
StartCellY = REAL_TO_INT_FLOOR(P0.Y/MAP_XY_FACTOR);
EndCellY = REAL_TO_INT_CEIL(P1.Y/MAP_XY_FACTOR);
}
Int i, j, minHt, maxHt;
minHt = m_map->getMaxHeightValue();
maxHt = 0;
for (j=StartCellY; j<=EndCellY; j++) {
for (i=StartCellX; i<=EndCellX; i++) {
Short cur = getClipHeight(i+m_map->getBorderSizeInline(),j+m_map->getBorderSizeInline());
if (cur<minHt) minHt = cur;
if (maxHt<cur) maxHt = cur;
}
}
Vector3 minPt(MAP_XY_FACTOR*(StartCellX-1), MAP_XY_FACTOR*(StartCellY-1), MAP_HEIGHT_SCALE*(minHt-1));
Vector3 maxPt(MAP_XY_FACTOR*(EndCellX+1), MAP_XY_FACTOR*(EndCellY+1), MAP_HEIGHT_SCALE*(maxHt+1));
MinMaxAABoxClass mmbox(minPt, maxPt);
hbox.Init(mmbox);
}
raytest.Result->ComputeContactPoint=true; //tell CollisionMath that we need point.
// Adjust indexes into the bordered height map.
StartCellX += m_map->getBorderSizeInline();
EndCellX += m_map->getBorderSizeInline();
StartCellY += m_map->getBorderSizeInline();
EndCellY += m_map->getBorderSizeInline();
Int offset;
for (offset = 1; offset < 5; offset *= 3) {
for (Y=StartCellY-offset; Y<=EndCellY+offset; Y++) {
for (X=StartCellX-offset; X<=EndCellX+offset; X++) {
//test the 2 triangles in this cell
// 3-----2
// | /|
// | / |
// |/ |
// 0-----1
//bottom triangle first
P0.X=ADJUST_FROM_INDEX_TO_REAL(X);
P0.Y=ADJUST_FROM_INDEX_TO_REAL(Y);
P0.Z=MAP_HEIGHT_SCALE*(float)getClipHeight(X, Y);
P1.X=ADJUST_FROM_INDEX_TO_REAL(X+1);
P1.Y=ADJUST_FROM_INDEX_TO_REAL(Y);
P1.Z=MAP_HEIGHT_SCALE*(float)getClipHeight(X+1, Y);
P2.X=ADJUST_FROM_INDEX_TO_REAL(X+1);
P2.Y=ADJUST_FROM_INDEX_TO_REAL(Y+1);
P2.Z=MAP_HEIGHT_SCALE*(float)getClipHeight(X+1, Y+1);
P3.X=ADJUST_FROM_INDEX_TO_REAL(X);
P3.Y=ADJUST_FROM_INDEX_TO_REAL(Y+1);
P3.Z=MAP_HEIGHT_SCALE*(float)getClipHeight(X, Y+1);
tri.V[0] = &P0;
tri.V[1] = &P1;
tri.V[2] = &P2;
tri.N = &normal;
tri.Compute_Normal();
hit = hit || (Bool)CollisionMath::Collide(raytest.Ray, tri, raytest.Result);
if (raytest.Result->StartBad)
return true;
//top triangle
tri.V[0] = &P2;
tri.V[1] = &P3;
tri.V[2] = &P0;
tri.N = &normal;
tri.Compute_Normal();
hit = hit || (Bool)CollisionMath::Collide(raytest.Ray, tri, raytest.Result);
if (hit)
raytest.Result->SurfaceType = SURFACE_TYPE_DEFAULT; ///@todo: WW3D uses this to return dirt, grass, etc. Do we need this?
}
// Don't break. It is possible to intersect 2 triangles, and the second is closer. if (hit) break;
}
// Don't break. It is possible to intersect 2 triangles, and the second is closer. if (hit) break;
}
return hit;
}
//=============================================================================
// BaseHeightMapRenderObjClass::getHeightMapHeight
//=============================================================================
/** return the height and normal of the triangle plane containing given location within heightmap. */
//=============================================================================
Real BaseHeightMapRenderObjClass::getHeightMapHeight(Real x, Real y, Coord3D* normal) const
{
// SORRY, KIDS
// Had to make this function logic safe, so,
// even though this is a renderObject, and is thus classified as client-side
// it is responsible for reporting height map heights (for reasons I can't say)
// but to do so safely, I a going to pass it the logical heighmap from the W3dTerrainVisual
// yes another nosequiter. Ugh!
// M Lorenzen
// by doing it this way the compiler won't call getLogicHeightMap twice...
WorldHeightMap *logicHeightMap = TheTerrainVisual?TheTerrainVisual->getLogicHeightMap():m_map;
if ( !logicHeightMap )
{
if (normal)
{
// return a default normal pointing up
normal->x = 0.0f;
normal->y = 0.0f;
normal->z = 1.0f;
}
return 0;
}
float height;
// 3-----2
// | /|
// | / |
// |/ |
// 0-----1
//Find surrounding grid points
const Real MAP_XY_FACTOR_INV = 1.0f / MAP_XY_FACTOR;
float xdiv = x * MAP_XY_FACTOR_INV;
float ydiv = y * MAP_XY_FACTOR_INV;
float ixf = FAST_REAL_FLOOR(xdiv);
float iyf = FAST_REAL_FLOOR(ydiv);
float fx = xdiv - ixf; //get fraction
float fy = ydiv - iyf; //get fraction
// since ixf & iyf are already floor'ed, we can use the fastest f->i conversion we have...
Int ix = fast_float2long_round(ixf) + logicHeightMap->getBorderSizeInline();
Int iy = fast_float2long_round(iyf) + logicHeightMap->getBorderSizeInline();
Int xExtent = logicHeightMap->getXExtent();
// Check for extent-3, not extent-1: we go into the next row/column of data for smoothed triangle points, so extent-1
// goes off the end...
if (ix > (xExtent-3) || iy > (logicHeightMap->getYExtent()-3) || iy < 1 || ix < 1)
{
// sample point is not on the heightmap
if (normal)
{
// return a default normal pointing up
normal->x = 0.0f;
normal->y = 0.0f;
normal->z = 1.0f;
}
return getClipHeight(ix, iy) * MAP_HEIGHT_SCALE;
}
const UnsignedByte* data = logicHeightMap->getDataPtr();
int idx = ix + iy*xExtent;
float p0 = data[idx];
float p2 = data[idx + xExtent + 1];
if (fy > fx) // test if we are in the upper triangle
{
float p3 = data[idx + xExtent];
height = (p3 + (1.0f-fy)*(p0-p3) + fx*(p2-p3)) * MAP_HEIGHT_SCALE;
}
else
{
// we are in the lower triangle
float p1 = data[idx + 1];
height = (p1 + fy*(p2-p1) + (1.0f-fx)*(p0-p1)) * MAP_HEIGHT_SCALE;
}
// DEBUG_ASSERTCRASH( height < 30, ("SOMEBODY THINKS THE CLIENT HEIGHTMAP IS GOOD ENOUGH FOR LOGIC SAMPLING."));
if (normal) {
// 9 8
//
//10 3-----2 7
// | /|
// | / |
// |/ |
//11 0-----1 6
//
// 4 5
//Find surrounding grid points for smoothed normals.
int idx4 = ix + (iy-1)*xExtent;
int idx0 = ix + iy*xExtent;
int idx3 = ix + iy*xExtent+xExtent;
int idx9 = ix + (iy+2)*xExtent;
UnsignedByte d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11;
d0 = data[idx0];
d1 = data[idx0+1];
d2 = data[idx3+1];
d3 = data[idx3];
d4 = data[idx4];
d5 = data[idx4+1];
d6 = data[idx0+2];
d7 = data[idx3+2];
d8 = data[idx9+1];
d9 = data[idx9];
d10 = data[idx3-1];
d11 = data[idx0-1];
Real deltaZ_X0 = d1-d11;
Real deltaZ_X1 = d6-d0;
Real deltaZ_X2 = d7-d3;
Real deltaZ_X3 = d6-d0;
Real deltaZ_Y0 = d3-d4;
Real deltaZ_Y1 = d2-d5;
Real deltaZ_Y2 = d8-d1;
Real deltaZ_Y3 = d9-d0;
// Interpolate to get the smoothed valued.
Real deltaZ_X_Left = deltaZ_X0*(1.0f-fx) + fx*deltaZ_X3;
Real deltaZ_X_Right = deltaZ_X1*(1.0f-fx) + fx*deltaZ_X2;
Real deltaZ_X = deltaZ_X_Left*(1.0-fy) + fy*deltaZ_X_Right;
Real deltaZ_Y_Left = deltaZ_Y0*(1.0f-fx) + fx*deltaZ_Y3;
Real deltaZ_Y_Right = deltaZ_Y1*(1.0f-fx) + fx*deltaZ_Y2;
Real deltaZ_Y = deltaZ_Y_Left*(1.0-fy) + fy*deltaZ_Y_Right;
Vector3 l2r, n2f, normalAtTexel;
l2r.Set(2*MAP_XY_FACTOR/MAP_HEIGHT_SCALE, 0, deltaZ_X);
n2f.Set(0, 2*MAP_XY_FACTOR/MAP_HEIGHT_SCALE, deltaZ_Y);
Vector3::Normalized_Cross_Product(l2r,n2f, &normalAtTexel);
normal->x = normalAtTexel.X;
normal->y = normalAtTexel.Y;
normal->z = normalAtTexel.Z;
}
return height;
}
//=============================================================================
Bool BaseHeightMapRenderObjClass::isClearLineOfSight(const Coord3D& pos, const Coord3D& posOther) const
{
if (m_map == nullptr)
return false; // doh. should not happen.
WorldHeightMap *logicHeightMap = TheTerrainVisual?TheTerrainVisual->getLogicHeightMap():m_map;