forked from electronicarts/CnC_Generals_Zero_Hour
-
Notifications
You must be signed in to change notification settings - Fork 184
Expand file tree
/
Copy pathW3DView.cpp
More file actions
3574 lines (3079 loc) · 120 KB
/
W3DView.cpp
File metadata and controls
3574 lines (3079 loc) · 120 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: W3DView.cpp //////////////////////////////////////////////////////////////////////////////
//
// W3D implementation of the game view class. This view allows us to have
// a "window" into the game world that can change its width, height as
// well as camera positioning controls
//
// Author: Colin Day, April 2001
//
///////////////////////////////////////////////////////////////////////////////////////////////////
// SYSTEM INCLUDES ////////////////////////////////////////////////////////////////////////////////
#include <stdlib.h>
#include <windows.h>
// USER INCLUDES //////////////////////////////////////////////////////////////////////////////////
#include "Lib/BaseType.h"
#include "Common/BuildAssistant.h"
#include "Common/FramePacer.h"
#include "Common/GameUtility.h"
#include "Common/GlobalData.h"
#include "Common/Module.h"
#include "Common/Radar.h"
#include "Common/RandomValue.h"
#include "Common/ThingTemplate.h"
#include "Common/ThingSort.h"
#include "Common/PerfTimer.h"
#include "Common/PlayerList.h"
#include "Common/Player.h"
#include "GameClient/Color.h"
#include "GameClient/CommandXlat.h"
#include "GameClient/Drawable.h"
#include "GameClient/GameClient.h"
#include "GameClient/GameWindowManager.h"
#include "GameClient/Image.h"
#include "GameClient/InGameUI.h"
#include "GameClient/Line2D.h"
#include "GameClient/SelectionInfo.h"
#include "GameClient/Shell.h"
#include "GameClient/TerrainVisual.h"
#include "GameClient/Water.h"
#include "GameLogic/AI.h" ///< For AI debug (yes, I'm cheating for now)
#include "GameLogic/AIPathfind.h" ///< For AI debug (yes, I'm cheating for now)
#include "GameLogic/ExperienceTracker.h"
#include "GameLogic/GameLogic.h"
#include "GameLogic/Module/AIUpdate.h"
#include "GameLogic/Module/BodyModule.h"
#include "GameLogic/Module/ContainModule.h"
#include "GameLogic/Module/OpenContain.h"
#include "GameLogic/Object.h"
#include "GameLogic/ScriptEngine.h"
#include "GameLogic/TerrainLogic.h" ///< @todo This should be TerrainVisual (client side)
#include "Common/AudioEventInfo.h"
#include "W3DDevice/Common/W3DConvert.h"
#include "W3DDevice/GameClient/HeightMap.h"
#include "W3DDevice/GameClient/W3DAssetManager.h"
#include "W3DDevice/GameClient/W3DDisplay.h"
#include "W3DDevice/GameClient/W3DScene.h"
#include "W3DDevice/GameClient/W3DView.h"
#include "d3dx8math.h"
#include "W3DDevice/GameClient/W3DShaderManager.h"
#include "W3DDevice/GameClient/Module/W3DModelDraw.h"
#include "W3DDevice/GameClient/W3DCustomScene.h"
#include "WW3D2/dx8renderer.h"
#include "WW3D2/light.h"
#include "WW3D2/camera.h"
#include "WW3D2/coltype.h"
#include "WW3D2/predlod.h"
#include "WW3D2/ww3d.h"
#include "W3DDevice/GameClient/CameraShakeSystem.h"
// 30 fps
Real TheW3DFrameLengthInMsec = MSEC_PER_LOGICFRAME_REAL; // default is 33msec/frame == 30fps. but we may change it depending on sys config.
static const Int MAX_REQUEST_CACHE_SIZE = 40; // Any size larger than 10, or examine code below for changes. jkmcd.
static const Real DRAWABLE_OVERSCAN = 75.0f; ///< 3D world coords of how much to overscan in the 3D screen region
constexpr const Real NearZ = MAP_XY_FACTOR; ///< Set the near to MAP_XY_FACTOR. Improves z buffer resolution.
//=================================================================================================
inline Real minf(Real a, Real b) { if (a < b) return a; else return b; }
inline Real maxf(Real a, Real b) { if (a > b) return a; else return b; }
//-------------------------------------------------------------------------------------------------
// Normalizes angle to +- PI.
//-------------------------------------------------------------------------------------------------
static void normAngle(Real &angle)
{
angle = WWMath::Normalize_Angle(angle);
}
#define TERRAIN_SAMPLE_SIZE 40.0f
static Real getHeightAroundPos(Real x, Real y)
{
// terrain height + desired height offset == cameraOffset * actual zoom
Real terrainHeight = TheTerrainLogic->getGroundHeight(x, y);
// find best approximation of max terrain height we can see
Real terrainHeightMax = terrainHeight;
terrainHeightMax = max(terrainHeightMax, TheTerrainLogic->getGroundHeight(x+TERRAIN_SAMPLE_SIZE, y-TERRAIN_SAMPLE_SIZE));
terrainHeightMax = max(terrainHeightMax, TheTerrainLogic->getGroundHeight(x-TERRAIN_SAMPLE_SIZE, y-TERRAIN_SAMPLE_SIZE));
terrainHeightMax = max(terrainHeightMax, TheTerrainLogic->getGroundHeight(x+TERRAIN_SAMPLE_SIZE, y+TERRAIN_SAMPLE_SIZE));
terrainHeightMax = max(terrainHeightMax, TheTerrainLogic->getGroundHeight(x-TERRAIN_SAMPLE_SIZE, y+TERRAIN_SAMPLE_SIZE));
return terrainHeightMax;
}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
W3DView::W3DView()
{
m_3DCamera = nullptr;
m_2DCamera = nullptr;
m_groundLevel = 10.0f;
#if PRESERVE_RETAIL_SCRIPTED_CAMERA
m_initialGroundLevel = m_groundLevel;
#endif
m_viewFilterMode = FM_VIEW_DEFAULT;
m_viewFilter = FT_VIEW_DEFAULT;
m_isWireFrameEnabled = m_nextWireFrameEnabled = FALSE;
m_shakeOffset.x = 0.0f;
m_shakeOffset.y = 0.0f;
m_shakeIntensity = 0.0f;
m_FXPitch = 1.0f;
m_freezeTimeForCameraMovement = false;
m_cameraHasMovedSinceRequest = true;
m_locationRequests.clear();
m_locationRequests.reserve(MAX_REQUEST_CACHE_SIZE + 10); // This prevents the vector from ever re-allocating
//Enhancements from CNC3 WST 4/15/2003. JSC Integrated 5/20/03.
m_scriptedState = 0;
m_CameraArrivedAtWaypointOnPathFlag = false; // Scripts for polling camera reached targets
m_isCameraSlaved = false; // This is for 3DSMax camera playback
m_useRealZoomCam = false; // true; //WST 10/18/2002
m_shakerAngles.X =0.0f; // Proper camera shake generator & sources
m_shakerAngles.Y =0.0f;
m_shakerAngles.Z =0.0f;
m_cameraAreaConstraints.zero();
m_recalcCamera = false;
}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
W3DView::~W3DView()
{
REF_PTR_RELEASE( m_2DCamera );
REF_PTR_RELEASE( m_3DCamera );
}
//-------------------------------------------------------------------------------------------------
/** Sets the height of the viewport, while maintaining original camera perspective. */
//-------------------------------------------------------------------------------------------------
void W3DView::setHeight(Int height)
{
// extend View functionality
View::setHeight(height);
Vector2 vMin,vMax;
m_3DCamera->Set_Aspect_Ratio((Real)getWidth()/(Real)height);
m_3DCamera->Get_Viewport(vMin,vMax);
vMax.Y=(Real)(m_originY+height)/(Real)TheDisplay->getHeight();
m_3DCamera->Set_Viewport(vMin,vMax);
// TheSuperHackers @bugfix Now recalculates the camera constraints because
// showing or hiding the control bar will change the viewable area.
m_cameraAreaConstraintsValid = false;
m_recalcCamera = true;
}
//-------------------------------------------------------------------------------------------------
/** Sets the width of the viewport, while maintaining original camera perspective. */
//-------------------------------------------------------------------------------------------------
void W3DView::setWidth(Int width)
{
// extend View functionality
View::setWidth(width);
Vector2 vMin,vMax;
m_3DCamera->Set_Aspect_Ratio((Real)width/(Real)getHeight());
m_3DCamera->Get_Viewport(vMin,vMax);
vMax.X=(Real)(m_originX+width)/(Real)TheDisplay->getWidth();
m_3DCamera->Set_Viewport(vMin,vMax);
//we want to maintain the same scale, so we'll need to adjust the fov.
//default W3D fov for full-screen is 50 degrees.
m_3DCamera->Set_View_Plane((Real)width/(Real)TheDisplay->getWidth()*DEG_TO_RADF(50.0f),-1);
m_cameraAreaConstraintsValid = false;
m_recalcCamera = true;
}
//-------------------------------------------------------------------------------------------------
/** Sets location of top-left view corner on display */
//-------------------------------------------------------------------------------------------------
void W3DView::setOrigin( Int x, Int y)
{
// extend View functionality
View::setOrigin(x,y);
Vector2 vMin,vMax;
m_3DCamera->Get_Viewport(vMin,vMax);
vMin.X=(Real)x/(Real)TheDisplay->getWidth();
vMin.Y=(Real)y/(Real)TheDisplay->getHeight();
m_3DCamera->Set_Viewport(vMin,vMax);
// bottom-right border was also moved my this call, so force an update of extents.
setWidth(m_width);
setHeight(m_height);
}
//-------------------------------------------------------------------------------------------------
/** @todo This is inefficient. We should construct the matrix directly using vectors. */
//-------------------------------------------------------------------------------------------------
#define MIN_CAPPED_ZOOM (0.5f) //WST 10.19.2002. JSC integrated 5/20/03.
void W3DView::buildCameraPosition( Vector3& sourcePos, Vector3& targetPos )
{
Real groundLevel = m_groundLevel; // 93.0f;
Real zoom = getZoom();
Real angle = getAngle();
Real pitch = getPitch();
Coord3D pos = *getPosition();
// add in the camera shake, if any
pos.x += m_shakeOffset.x;
pos.y += m_shakeOffset.y;
// TheSuperHackers @info The default pitch affects the look-at distance to the target.
// This is strange math which would need special attention when changed.
sourcePos.Z = getCameraOffsetZ();
sourcePos.Y = -(sourcePos.Z / tan(ViewDefaultPitchRadians));
sourcePos.X = -(sourcePos.Y * tan(ViewDefaultYawRadians));
// set position of camera itself
if (m_useRealZoomCam) //WST 10/10/2002 Real Zoom using FOV
{
Real cappedZoom = clamp(MIN_CAPPED_ZOOM, zoom, 1.0f);
m_FOV = DEG_TO_RADF(50.0f) * cappedZoom * cappedZoom;
}
else
{
sourcePos.X *= zoom;
sourcePos.Y *= zoom;
sourcePos.Z *= zoom;
}
// camera looking at origin
targetPos.X = 0;
targetPos.Y = 0;
targetPos.Z = 0;
// TheSuperHackers @info Scales the source position later by this much
// to achieve the intended camera height. Must not scale before pitching!
const Real heightScale = 1.0f - (groundLevel / sourcePos.Z);
// construct a matrix to rotate around the up vector by the given angle
const Matrix3D angleTransform( Vector3( 0.0f, 0.0f, 1.0f ), angle - ViewDefaultYawRadians );
// construct a matrix to rotate around the left vector by the given angle
const Matrix3D pitchTransform( Vector3( -1.0f, 0.0f, 0.0f ), pitch - ViewDefaultPitchRadians );
// rotate camera position (pitch, then angle)
#ifdef ALLOW_TEMPORARIES
sourcePos = pitchTransform * sourcePos;
sourcePos = angleTransform * sourcePos;
#else
pitchTransform.mulVector3(sourcePos);
angleTransform.mulVector3(sourcePos);
#endif
sourcePos *= heightScale;
// set look at position
targetPos.X += pos.x;
targetPos.Y += pos.y;
targetPos.Z += groundLevel;
// translate to world space
sourcePos += targetPos;
// do m_FXPitch adjustment.
//WST Real height = sourcePos.Z - targetPos.Z;
//WST height *= m_FXPitch;
//WST targetPos.Z = sourcePos.Z - height;
// The following code moves camera down and pitch up when player zooms in.
// Use scripts to switch to useRealZoomCam
if (m_useRealZoomCam)
{
Real pitchAdjust = 1.0f;
if (!TheDisplay->isLetterBoxed())
{
Real cappedZoom = clamp(MIN_CAPPED_ZOOM, zoom, 1.0f);
sourcePos.Z = sourcePos.Z * (0.5f + cappedZoom * 0.5f); // move camera down physically
pitchAdjust = cappedZoom; // adjust camera to pitch up
}
m_FXPitch = 1.0f * (0.25f + pitchAdjust*0.75f);
sourcePos.X = targetPos.X + ((sourcePos.X - targetPos.X) / m_FXPitch);
sourcePos.Y = targetPos.Y + ((sourcePos.Y - targetPos.Y) / m_FXPitch);
}
else
{
// TheSuperHackers @todo Investigate whether the non Generals code is correct for Zero Hour.
// It certainly is incorrect for Generals when m_FXPitch goes above 1:
// Seen in USA mission 1 second cut scene with SCUD Storm.
#if RTS_GENERALS
Real height = sourcePos.Z - targetPos.Z;
height *= m_FXPitch;
targetPos.Z = sourcePos.Z - height;
#else
if (m_FXPitch <= 1.0f)
{
targetPos.Z = sourcePos.Z - ((sourcePos.Z - targetPos.Z) * m_FXPitch);
}
else
{
sourcePos.X = targetPos.X + ((sourcePos.X - targetPos.X) / m_FXPitch);
sourcePos.Y = targetPos.Y + ((sourcePos.Y - targetPos.Y) / m_FXPitch);
}
#endif
}
}
void W3DView::buildCameraTransform( Matrix3D *transform, const Vector3 &sourcePos, const Vector3 &targetPos )
{
//m_3DCamera->Set_View_Plane(DEG_TO_RADF(50.0f));
//DEBUG_LOG(("zoom %f, SourceZ %f, posZ %f, groundLevel %f CamOffZ %f",
// zoom, sourcePos.Z, pos.z, groundLevel, getCameraOffsetZ()));
// build new camera transform
transform->Make_Identity();
transform->Look_At( sourcePos, targetPos, 0 );
//WST 11/12/2002 New camera shaker system
// TheSuperHackers @tweak The camera shaker is now decoupled from the render update.
// TheSuperHackers @todo Move Update_Camera_Shaker to the W3DView::update function.
CameraShakerSystem.Timestep(TheFramePacer->getLogicTimeStepMilliseconds());
CameraShakerSystem.Update_Camera_Shaker(sourcePos, &m_shakerAngles);
transform->Rotate_X(m_shakerAngles.X);
transform->Rotate_Y(m_shakerAngles.Y);
transform->Rotate_Z(m_shakerAngles.Z);
//if (m_shakerAngles.X >= 0.0f)
//{
// DEBUG_LOG(("m_shakerAngles %f, %f, %f", m_shakerAngles.X, m_shakerAngles.Y, m_shakerAngles.Z));
//}
// (gth) check if the camera is being controlled by an animation
if (m_isCameraSlaved) {
// find object named m_cameraSlaveObjectName
Object * obj = TheScriptEngine->getUnitNamed(m_cameraSlaveObjectName);
if (obj != nullptr) {
// dig out the drawable
Drawable * draw = obj->getDrawable();
if (draw != nullptr) {
// dig out the first draw module with an ObjectDrawInterface
for (DrawModule ** dm = draw->getDrawModules(); *dm; ++dm) {
const ObjectDrawInterface* di = (*dm)->getObjectDrawInterface();
if (di) {
Matrix3D tm;
di->clientOnly_getRenderObjBoneTransform(m_cameraSlaveObjectBoneName,&tm);
// Ok, slam it into the camera!
*transform = tm;
//--------------------------------------------------------------------
// WST 10.22.2002. Update the Listener positions used by audio system
//--------------------------------------------------------------------
Vector3 position = transform->Get_Translation();
Coord3D coord;
coord.set(position.X, position.Y, position.Z);
View::setPosition(&coord);
break;
}
}
} else {
m_isCameraSlaved = false;
}
} else {
m_isCameraSlaved = false;
}
}
}
//-------------------------------------------------------------------------------------------------
// TheSuperHackers @info Original logic responsible for zooming the camera to the desired height.
Bool W3DView::zoomCameraToDesiredHeight()
{
const Real desiredZoom = getDesiredZoom(m_pos.x, m_pos.y);
const Real adjustZoom = desiredZoom - m_zoom;
if (fabs(adjustZoom) >= 0.001f)
{
const Real fpsRatio = TheFramePacer->getBaseOverUpdateFpsRatio();
const Real adjustFactor = std::min(TheGlobalData->m_cameraAdjustSpeed * fpsRatio, 1.0f);
m_zoom += adjustZoom * adjustFactor;
return true;
}
return false;
}
//-------------------------------------------------------------------------------------------------
// TheSuperHackers @bugfix New logic responsible for moving the camera pivot to the terrain ground.
// This is essential to correctly center the camera above the ground when playing.
Bool W3DView::movePivotToGround()
{
const Real groundLevel = m_groundLevel;
const Real groundLevelDiff = m_terrainHeightAtPivot - groundLevel;
if (fabs(groundLevelDiff) > 0.1f)
{
const Real fpsRatio = TheFramePacer->getBaseOverUpdateFpsRatio();
const Real adjustFactor = std::min(TheGlobalData->m_cameraAdjustSpeed * fpsRatio, 1.0f);
// Adjust the ground level. This will change the world height of the camera.
m_groundLevel += groundLevelDiff * adjustFactor;
// Reposition the camera relative to its pitch.
// This effectively zooms the camera in the view direction together with the ground level change.
Vector3 sourcePos;
Vector3 targetPos;
buildCameraPosition(sourcePos, targetPos);
const Vector3 delta = targetPos - sourcePos;
if (fabs(delta.Z) > 0.1f)
{
Vector2 groundLevelCenter;
Vector2 terrainHeightCenter;
groundLevelCenter.X = Vector3::Find_X_At_Z(groundLevel, sourcePos, targetPos);
groundLevelCenter.Y = Vector3::Find_Y_At_Z(groundLevel, sourcePos, targetPos);
terrainHeightCenter.X = Vector3::Find_X_At_Z(m_terrainHeightAtPivot, sourcePos, targetPos);
terrainHeightCenter.Y = Vector3::Find_Y_At_Z(m_terrainHeightAtPivot, sourcePos, targetPos);
Vector2 posDiff = terrainHeightCenter - groundLevelCenter;
// Adjust the strength of the repositioning for low camera pitch, because
// it feels bad to move the camera around when it looks over the terrain.
const Real pitch = WWMath::Asin(fabs(delta.Z) / delta.Length());
constexpr const Real lowerPitch = DEG_TO_RADF(15.f);
constexpr const Real upperPitch = DEG_TO_RADF(30.f);
Real repositionStrength = WWMath::Inverse_Lerp(lowerPitch, upperPitch, pitch);
repositionStrength = WWMath::Clamp(repositionStrength, 0.0f, 1.0f);
posDiff *= repositionStrength;
Coord3D pos = *getPosition();
pos.x += posDiff.X * adjustFactor;
pos.y += posDiff.Y * adjustFactor;
setPosition(&pos);
}
return true;
}
return false;
}
void W3DView::updateCameraAreaConstraints()
{
#if defined(RTS_DEBUG)
if (!TheGlobalData->m_useCameraConstraints)
return;
#endif
if (!m_cameraAreaConstraintsValid)
{
calcCameraAreaConstraints();
}
if (m_cameraAreaConstraintsValid && !isWithinCameraAreaConstraints())
{
clipCameraIntoAreaConstraints();
m_recalcCamera = true;
}
}
//-------------------------------------------------------------------------------------------------
/*
Note the following restrictions on camera constraints!
-- they assume that all maps are height 'm_groundLevel' at the edges.
(since you need to add some "buffer" around the edges of your map
anyway, this shouldn't be an issue.)
-- for angles/pitches other than zero, it may show boundaries.
since we currently plan the game to be restricted to this,
it shouldn't be an issue.
*/
void W3DView::calcCameraAreaConstraints()
{
// DEBUG_LOG(("*** rebuilding cam constraints"));
// ok, now check to ensure that we can't see outside the map region,
// and twiddle the camera if needed
if (TheTerrainLogic)
{
Region3D mapRegion;
TheTerrainLogic->getExtent( &mapRegion );
// Update the 3D camera before using its transform to calculate the constraints with.
Vector3 sourcePos;
Vector3 targetPos;
buildCameraPosition(sourcePos, targetPos);
Matrix3D cameraTransform;
buildCameraTransform(&cameraTransform, sourcePos, targetPos);
Matrix3D prevCameraTransform = m_3DCamera->Get_Transform();
m_3DCamera->Set_Transform(cameraTransform);
Real offset = calcCameraAreaOffset(m_groundLevel);
offset = std::min(offset, (mapRegion.hi.x - mapRegion.lo.x) / 2);
offset = std::min(offset, (mapRegion.hi.y - mapRegion.lo.y) / 2);
// Revert the 3D camera transform.
m_3DCamera->Set_Transform(prevCameraTransform);
m_cameraAreaConstraints.lo.x = mapRegion.lo.x + offset;
m_cameraAreaConstraints.hi.x = mapRegion.hi.x - offset;
m_cameraAreaConstraints.lo.y = mapRegion.lo.y + offset;
m_cameraAreaConstraints.hi.y = mapRegion.hi.y - offset;
m_cameraAreaConstraintsValid = true;
}
}
//-------------------------------------------------------------------------------------------------
Real W3DView::calcCameraAreaOffset(Real maxEdgeZ)
{
Coord2D center;
ICoord2D screen;
Vector3 rayStart;
Vector3 rayEnd;
// Pick at the center
screen.x = 0.5f * getWidth() + m_originX;
screen.y = 0.5f * getHeight() + m_originY;
getPickRay(&screen, &rayStart, &rayEnd);
// Looking at the horizon would yield infinite numbers.
if (fabs(rayStart.Z - rayEnd.Z) < 1.0f)
return 1e+6f;
center.x = Vector3::Find_X_At_Z(maxEdgeZ, rayStart, rayEnd);
center.y = Vector3::Find_Y_At_Z(maxEdgeZ, rayStart, rayEnd);
const Bool isLookingDown = rayStart.Z >= rayEnd.Z;
const Real height = isLookingDown ? getHeight() : 0.0f;
screen.y = height + m_originY;
getPickRay(&screen, &rayStart, &rayEnd);
Real bottomX = Vector3::Find_X_At_Z(maxEdgeZ, rayStart, rayEnd);
Real bottomY = Vector3::Find_Y_At_Z(maxEdgeZ, rayStart, rayEnd);
center.x -= bottomX;
center.y -= bottomY;
Real offset = center.length();
// TheSuperHackers @tweak Reduces the offset to allow scrolling closer to the edges.
offset *= 0.85f;
if (TheGlobalData->m_debugAI) {
offset -= 1000; // push out the constraints so we can look at staging areas.
}
return offset;
}
//-------------------------------------------------------------------------------------------------
void W3DView::clipCameraIntoAreaConstraints()
{
constexpr const Real eps = 1e-6f;
Coord3D pos = *getPosition();
pos.x = clamp(m_cameraAreaConstraints.lo.x + eps, pos.x, m_cameraAreaConstraints.hi.x - eps);
pos.y = clamp(m_cameraAreaConstraints.lo.y + eps, pos.y, m_cameraAreaConstraints.hi.y - eps);
setPosition(&pos);
}
//-------------------------------------------------------------------------------------------------
Bool W3DView::isWithinCameraAreaConstraints() const
{
const Coord3D* pos = getPosition();
return m_cameraAreaConstraints.isInRegion(pos->x, pos->y);
}
//-------------------------------------------------------------------------------------------------
Bool W3DView::isWithinCameraHeightConstraints() const
{
const Bool isAboveMinHeight = m_currentHeightAboveGround >= m_minHeightAboveGround;
const Bool isBelowMaxHeight = m_currentHeightAboveGround <= m_maxHeightAboveGround;
return isAboveMinHeight && (isBelowMaxHeight || !TheGlobalData->m_enforceMaxCameraHeight);
}
//-------------------------------------------------------------------------------------------------
/** Returns a world-space ray originating at a given screen pixel position
and ending at the far clip plane for current camera. Screen coordinates
assumed in absolute values relative to full display resolution.*/
//-------------------------------------------------------------------------------------------------
void W3DView::getPickRay(const ICoord2D *screen, Vector3 *rayStart, Vector3 *rayEnd)
{
Real logX;
Real logY;
Real screenX = screen->x - m_originX;
Real screenY = screen->y - m_originY;
//W3D Screen coordinates are -1 to 1, so we need to do some conversion:
PixelScreenToW3DLogicalScreen(screenX, screenY, &logX, &logY, getWidth(), getHeight());
*rayStart = m_3DCamera->Get_Position(); //get camera location
m_3DCamera->Un_Project(*rayEnd,Vector2(logX,logY)); //get world space point
*rayEnd -= *rayStart; //vector camera to world space point
rayEnd->Normalize(); //make unit vector
*rayEnd *= m_3DCamera->Get_Depth(); //adjust length to reach far clip plane
*rayEnd += *rayStart; //get point on far clip plane along ray from camera.
}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
Real W3DView::getCameraOffsetZ() const
{
#if PRESERVE_RETAIL_SCRIPTED_CAMERA
// TheSuperHackers @info xezon 04/12/2025 It is necessary to use the initial ground level for the
// scripted camera height to preserve the original look of it. Otherwise the forward distance
// of the camera will slightly change the view pitch.
if (!m_isUserControlled)
{
return m_initialGroundLevel + TheGlobalData->m_cameraHeight;
}
#endif
return m_groundLevel + TheGlobalData->m_maxCameraHeight;
}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
Real W3DView::getDesiredHeight(Real x, Real y) const
{
#if PRESERVE_RETAIL_SCRIPTED_CAMERA
// TheSuperHackers @info xezon 06/12/2025 The height above ground must be relative to the current
// terrain height because the ground level is not updated for it.
if (!m_isUserControlled)
{
return getHeightAroundPos(x, y) + m_heightAboveGround;
}
#endif
return m_groundLevel + m_heightAboveGround;
}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
Real W3DView::getMaxHeight(Real x, Real y) const
{
#if PRESERVE_RETAIL_SCRIPTED_CAMERA
if (!m_isUserControlled)
{
return getHeightAroundPos(x, y) + m_maxHeightAboveGround;
}
#endif
return m_groundLevel + m_maxHeightAboveGround;
}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
Real W3DView::getDesiredZoom(Real x, Real y) const
{
return getDesiredHeight(x, y) / getCameraOffsetZ();
}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
Real W3DView::getMaxZoom(Real x, Real y) const
{
return getMaxHeight(x, y) / getCameraOffsetZ();
}
//-------------------------------------------------------------------------------------------------
/** set the transform matrix of m_3DCamera, based on m_pos & m_angle */
//-------------------------------------------------------------------------------------------------
void W3DView::setCameraTransform()
{
if (TheGlobalData->m_headless)
return;
m_cameraHasMovedSinceRequest = true;
Real farZ = 1200.0f;
if (m_useRealZoomCam) //WST 10.19.2002
{
if (m_FXPitch<0.95f)
{
farZ = farZ / m_FXPitch; //Extend far Z when we pitch up for RealZoomCam
}
}
else
{
if ((TheGlobalData->m_drawEntireTerrain) || (m_FXPitch<0.95f || m_zoom>1.05))
{ //need to extend far clip plane so entire terrain can be visible
farZ *= MAP_XY_FACTOR;
}
}
m_3DCamera->Set_Clip_Planes(NearZ, farZ);
#if defined(RTS_DEBUG)
m_3DCamera->Set_View_Plane( m_FOV, -1 );
#endif
// rebuild it (even if we just did it due to camera constraints)
Vector3 sourcePos;
Vector3 targetPos;
buildCameraPosition(sourcePos, targetPos);
Matrix3D cameraTransform;
buildCameraTransform(&cameraTransform, sourcePos, targetPos);
m_3DCamera->Set_Transform( cameraTransform );
if (TheTerrainRenderObject)
{
updateTerrain();
}
// TheSuperHackers @fix Notify the Radar about the changed view always.
// This way the radar view box should always be in sync with the camera view.
if (TheRadar)
{
TheRadar->notifyViewChanged();
}
}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
void W3DView::init()
{
// extend View functionality
View::init();
setName("W3DView");
// set default camera "look at" point
Coord3D pos;
pos.x = 87.0f;
pos.y = 77.0f;
pos.z = 0;
pos.x *= MAP_XY_FACTOR;
pos.y *= MAP_XY_FACTOR;
setPosition(&pos);
// create our 3D camera
m_3DCamera = NEW_REF( CameraClass, () );
// create our 2D camera for the GUI overlay
m_2DCamera = NEW_REF( CameraClass, () );
m_2DCamera->Set_Position( Vector3( 0, 0, 1 ) );
Vector2 min = Vector2( -1, -0.75f );
Vector2 max = Vector2( +1, +0.75f );
m_2DCamera->Set_View_Plane( min, max );
m_2DCamera->Set_Clip_Planes( 0.995f, 2.0f );
m_scrollAmountCutoffSqr = sqr(TheGlobalData->m_scrollAmountCutoff);
m_cameraAreaConstraintsValid = false;
m_recalcCameraConstraintsAfterScrolling = false;
m_recalcCamera = true;
}
//-------------------------------------------------------------------------------------------------
const Coord3D& W3DView::get3DCameraPosition() const
{
Vector3 camera = m_3DCamera->Get_Position();
static Coord3D pos;
pos.set( camera.X, camera.Y, camera.Z );
return pos;
}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
void W3DView::reset()
{
View::reset();
// Just in case...
setTimeMultiplier(1); // Set time rate back to 1.
stopDoingScriptedCamera();
setUserControlled(true);
// Just move the camera to zero. It'll get repositioned at the beginning of the next game anyways.
Coord3D arbitraryPos = { 0, 0, 0 };
setPosition(&arbitraryPos);
setAngleToDefault();
setPitchToDefault();
setZoomToDefault();
setViewFilter(FT_VIEW_DEFAULT);
Coord2D gb = { 0,0 };
setGuardBandBias( &gb );
m_recalcCameraConstraintsAfterScrolling = false;
}
//-------------------------------------------------------------------------------------------------
/** draw worker for drawables in the view region */
//-------------------------------------------------------------------------------------------------
static void drawDrawable( Drawable *draw, void *userData )
{
draw->draw();
}
// ------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
static void drawTerrainNormal( Drawable *draw, void *userData )
{
UnsignedInt color = GameMakeColor( 255, 255, 0, 255 );
if (TheTerrainLogic)
{
Coord3D pos = *draw->getPosition();
Coord3D normal;
pos.z = TheTerrainLogic->getGroundHeight(pos.x, pos.y, &normal);
const Real NORMLEN = 20;
normal.x = pos.x + normal.x * NORMLEN;
normal.y = pos.y + normal.y * NORMLEN;
normal.z = pos.z + normal.z * NORMLEN;
ICoord2D start, end;
TheTacticalView->worldToScreen(&pos, &start);
TheTacticalView->worldToScreen(&normal, &end);
TheDisplay->drawLine(start.x, start.y, end.x, end.y, 1.0f, color);
}
}
#if defined(RTS_DEBUG)
// ------------------------------------------------------------------------------------------------
// Draw a crude circle. Appears on top of any world geometry
// ------------------------------------------------------------------------------------------------
void drawDebugCircle( const Coord3D & center, Real radius, Real width, Color color )
{
const Real inc = PI/4.0f;
Real angle = 0.0f;
Coord3D pnt, lastPnt;
ICoord2D start, end;
Bool endValid, startValid;
lastPnt.x = center.x + radius * (Real)cos(angle);
lastPnt.y = center.y + radius * (Real)sin(angle);
lastPnt.z = center.z;
endValid = ( TheTacticalView->worldToScreenTriReturn( &lastPnt, &end ) != View::WTS_INVALID );
for( angle = inc; angle <= 2.0f * PI; angle += inc )
{
pnt.x = center.x + radius * (Real)cos(angle);
pnt.y = center.y + radius * (Real)sin(angle);
pnt.z = center.z;
startValid = ( TheTacticalView->worldToScreenTriReturn( &pnt, &start ) != View::WTS_INVALID );
if ( startValid && endValid )
TheDisplay->drawLine( start.x, start.y, end.x, end.y, width, color );
lastPnt = pnt;
end = start;
endValid = startValid;
}
}
static void drawDrawableExtents( Drawable *draw, void *userData ); // FORWARD DECLARATION
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
static void drawContainedDrawable( Object *obj, void *userData )
{
Drawable *draw = obj->getDrawable();
if( draw )
drawDrawableExtents( draw, userData );
}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
static void drawDrawableExtents( Drawable *draw, void *userData )
{
UnsignedInt color = GameMakeColor( 0, 255, 0, 255 );
switch( draw->getDrawableGeometryInfo().getGeomType() )
{
//---------------------------------------------------------------------------------------------
case GEOMETRY_BOX:
{
Real angle = draw->getOrientation();
Real c = (Real)cos(angle);
Real s = (Real)sin(angle);
Real exc = draw->getDrawableGeometryInfo().getMajorRadius()*c;
Real eyc = draw->getDrawableGeometryInfo().getMinorRadius()*c;
Real exs = draw->getDrawableGeometryInfo().getMajorRadius()*s;
Real eys = draw->getDrawableGeometryInfo().getMinorRadius()*s;
Coord3D pts[4];
pts[0].x = draw->getPosition()->x - exc - eys;
pts[0].y = draw->getPosition()->y + eyc - exs;
pts[0].z = 0;
pts[1].x = draw->getPosition()->x + exc - eys;
pts[1].y = draw->getPosition()->y + eyc + exs;
pts[1].z = 0;
pts[2].x = draw->getPosition()->x + exc + eys;
pts[2].y = draw->getPosition()->y - eyc + exs;
pts[2].z = 0;
pts[3].x = draw->getPosition()->x - exc + eys;
pts[3].y = draw->getPosition()->y - eyc - exs;
pts[3].z = 0;
Real z = draw->getPosition()->z;
for( int i = 0; i < 2; i++ )
{
for (int corner = 0; corner < 4; corner++)
{
ICoord2D start, end;
pts[corner].z = z;
pts[(corner+1)&3].z = z;
TheTacticalView->worldToScreen(&pts[corner], &start);
TheTacticalView->worldToScreen(&pts[(corner+1)&3], &end);
TheDisplay->drawLine(start.x, start.y, end.x, end.y, 1.0f, color);
}
z += draw->getDrawableGeometryInfo().getMaxHeightAbovePosition();
}
break;
}
//---------------------------------------------------------------------------------------------
case GEOMETRY_SPHERE: // not quite right, but close enough
case GEOMETRY_CYLINDER:
{
Coord3D center = *draw->getPosition();
const Real radius = draw->getDrawableGeometryInfo().getMajorRadius();
// draw cylinder
for( int i=0; i<2; i++ )
{
drawDebugCircle( center, radius, 1.0f, color );
// next time 'round, draw the top of the cylinder
center.z += draw->getDrawableGeometryInfo().getMaxHeightAbovePosition();
}
// draw centerline
ICoord2D start, end;
center = *draw->getPosition();
TheTacticalView->worldToScreen( ¢er, &start );
center.z += draw->getDrawableGeometryInfo().getMaxHeightAbovePosition();
TheTacticalView->worldToScreen( ¢er, &end );
TheDisplay->drawLine( start.x, start.y, end.x, end.y, 1.0f, color );
break;
}
}
// draw any extents for things that are contained by this
Object *obj = draw->getObject();
if( obj )