/
CSpaceObject.cpp
7709 lines (5782 loc) · 182 KB
/
CSpaceObject.cpp
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
// CSpaceObject.cpp
//
// CSpaceObject class
// Copyright (c) 2019 Kronosaur Productions, LLC. All Rights Reserved.
#include "PreComp.h"
#ifdef DEBUG_ON_CREATE_TIME
#include <stdio.h>
static DWORD g_dwTotalTime = 0;
#endif
#define MAX_DELTA (2.0 * g_KlicksPerPixel)
#define MAX_DELTA2 (MAX_DELTA * MAX_DELTA)
#define MAX_DELTA_VEL (g_KlicksPerPixel / 2.0)
#define MAX_DELTA_VEL2 (MAX_DELTA_VEL * MAX_DELTA_VEL)
const int ITEM_UPDATE_CYCLE = 30;
const int HIGHLIGHT_TIMER = 200;
const int HIGHLIGHT_BLINK = 110;
const int HIGHLIGHT_FADE = 30;
const int ANNOTATION_INNER_SPACING_Y = 2;
const int DAMAGE_BAR_WIDTH = 100;
const int DAMAGE_BAR_HEIGHT = 12;
const Metric g_rMaxCommsRange = (LIGHT_MINUTE * 60.0);
const Metric g_rMaxCommsRange2 = (g_rMaxCommsRange * g_rMaxCommsRange);
#define BOUNDS_CHECK_DIST (256.0 * g_KlicksPerPixel)
#define BOUNDS_CHECK_DIST2 (BOUNDS_CHECK_DIST * BOUNDS_CHECK_DIST)
#define HIGHLIGHT_CORNER_WIDTH 8
#define HIGHLIGHT_CORNER_HEIGHT 8
#define STR_UNCHARTED CONSTLIT("uncharted")
#define CAN_DOCK_AS_PLAYER_EVENT CONSTLIT("CanDockAsPlayer")
#define CAN_INSTALL_ITEM_EVENT CONSTLIT("CanInstallItem")
#define GET_DOCK_SCREEN_EVENT CONSTLIT("GetDockScreen")
#define GET_EXPLOSION_TYPE_EVENT CONSTLIT("GetExplosionType")
#define GET_PLAYER_PRICE_ADJ_EVENT CONSTLIT("GetPlayerPriceAdj")
#define ON_ATTACKED_EVENT CONSTLIT("OnAttacked")
#define ON_ATTACKED_BY_PLAYER_EVENT CONSTLIT("OnAttackedByPlayer")
#define ON_CREATE_EVENT CONSTLIT("OnCreate")
#define ON_CREATE_ORDERS_EVENT CONSTLIT("OnCreateOrders")
#define ON_DAMAGE_EVENT CONSTLIT("OnDamage")
#define ON_DATA_TRANSFER_EVENT CONSTLIT("OnDataTransfer")
#define ON_DESELECTED_EVENT CONSTLIT("OnDeselected")
#define ON_DESTROY_EVENT CONSTLIT("OnDestroy")
#define ON_DESTROY_CHECK_EVENT CONSTLIT("OnDestroyCheck")
#define ON_DESTROY_OBJ_EVENT CONSTLIT("OnDestroyObj")
#define ON_DOCK_OBJ_ADJ_EVENT CONSTLIT("OnDockObjAdj")
#define ON_DOCK_OBJ_DESTROYED_EVENT CONSTLIT("OnDockObjDestroyed")
#define ON_ENTERED_GATE_EVENT CONSTLIT("OnEnteredGate")
#define ON_ENTERED_SYSTEM_EVENT CONSTLIT("OnEnteredSystem")
#define ON_LOAD_EVENT CONSTLIT("OnLoad")
#define ON_MINING_EVENT CONSTLIT("OnMining")
#define ON_OBJ_BLACKLISTED_PLAYER_EVENT CONSTLIT("OnObjBlacklistedPlayer")
#define ON_OBJ_DESTROYED_EVENT CONSTLIT("OnObjDestroyed")
#define ON_OBJ_DOCKED_EVENT CONSTLIT("OnObjDocked")
#define ON_OBJ_ENTERED_GATE_EVENT CONSTLIT("OnObjEnteredGate")
#define ON_OBJ_GATE_EVENT CONSTLIT("OnObjGate")
#define ON_OBJ_GATE_CHECK_EVENT CONSTLIT("OnObjGateCheck")
#define ON_OBJ_JUMPED_EVENT CONSTLIT("OnObjJumped")
#define ON_OBJ_JUMP_POS_ADJ_EVENT CONSTLIT("OnObjJumpPosAdj")
#define ON_OBJ_RECONNED_EVENT CONSTLIT("OnObjReconned")
#define ON_ORDER_CHANGED_EVENT CONSTLIT("OnOrderChanged")
#define ON_ORDERS_COMPLETED_EVENT CONSTLIT("OnOrdersCompleted")
#define ON_OVERRIDE_INIT_EVENT CONSTLIT("OnEventHandlerInit")
#define ON_OVERRIDE_TERM_EVENT CONSTLIT("OnEventHandlerTerm")
#define ON_MISSION_ACCEPTED_EVENT CONSTLIT("OnMissionAccepted")
#define ON_MISSION_COMPLETED_EVENT CONSTLIT("OnMissionCompleted")
#define ON_PLAYER_BLACKLISTED_EVENT CONSTLIT("OnPlayerBlacklisted")
#define ON_PLAYER_ENTERED_SHIP_EVENT CONSTLIT("OnPlayerEnteredShip")
#define ON_PLAYER_ENTERED_SYSTEM_EVENT CONSTLIT("OnPlayerEnteredSystem")
#define ON_PLAYER_LEFT_SHIP_EVENT CONSTLIT("OnPlayerLeftShip")
#define ON_PLAYER_LEFT_SYSTEM_EVENT CONSTLIT("OnPlayerLeftSystem")
#define ON_RANDOM_ENCOUNTER_EVENT CONSTLIT("OnRandomEncounter")
#define ON_SELECTED_EVENT CONSTLIT("OnSelected")
#define ON_SUBORDINATE_ATTACKED_EVENT CONSTLIT("OnSubordinateAttacked")
#define ON_SYSTEM_EXPLOSION_EVENT CONSTLIT("OnSystemExplosion")
#define ON_SYSTEM_OBJ_DESTROYED_EVENT CONSTLIT("OnSystemObjDestroyed")
#define ON_SYSTEM_STARTED_EVENT CONSTLIT("OnSystemStarted")
#define ON_SYSTEM_STOPPED_EVENT CONSTLIT("OnSystemStopped")
#define ON_SYSTEM_WEAPON_FIRE_EVENT CONSTLIT("OnSystemWeaponFire")
#define ON_TRANSLATE_MESSAGE_EVENT CONSTLIT("OnTranslateMessage")
#define ON_UPDATE_EVENT CONSTLIT("OnUpdate")
#define FIELD_ARMOR_INTEGRITY CONSTLIT("armorIntegrity")
#define FIELD_HULL_INTEGRITY CONSTLIT("hullIntegrity")
#define FIELD_OBJ_ID CONSTLIT("objID")
#define FIELD_POS CONSTLIT("pos")
#define FIELD_SHIELD_LEVEL CONSTLIT("shieldLevel")
#define FIELD_STATUS CONSTLIT("status")
#define LANGID_DOCKING_REQUEST_DENIED CONSTLIT("core.dockingRequestDenied")
#define ORDER_DOCKED CONSTLIT("docked")
#define PROPERTY_CORE_MINING_DIFFICULTY CONSTLIT("core.miningDifficulty")
#define SPECIAL_CHARACTER CONSTLIT("character:")
#define SPECIAL_DATA CONSTLIT("data:")
#define SPECIAL_IS_PLANET CONSTLIT("isPlanet:")
#define SPECIAL_LOCATION CONSTLIT("location:")
#define SPECIAL_PROPERTY CONSTLIT("property:")
#define SPECIAL_UNID CONSTLIT("unid:")
#define SPECIAL_VALUE_TRUE CONSTLIT("true")
static Metric g_rMaxPerceptionRange[CSpaceObject::perceptMax+1] =
{
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
};
struct SInstallItemResultsData
{
char *pszID;
int iArmorCompatibleID;
int iDeviceCompatibleID;
};
SInstallItemResultsData INSTALL_ITEM_RESULTS_TABLE[] =
{
{ "ok", 0, 0, },
{ "armorTooHeavy", 1, -1, },
{ "cannotInstall", -1, -1, },
{ "noDeviceSlotsLeft", -1, 2 },
{ "noNonWeaponSlotsLeft", -1, 13 },
{ "noWeaponSlotsLeft", -1, 12 },
{ "notInstallable", -1, 1 },
{ "reactorIncompatible", -1, 11 },
{ "reactorOverload", -1, -1 },
{ "reactorTooWeak", -1, 7 },
{ "notCompatible", -1, -1 },
{ "tooMuchCargo", -1, -1 },
{ "replacementRequired", -1, 8 },
{ "replacementRequired", -1, 5 },
{ "replacementRequired", -1, 6 },
{ "replacementRequired", -1, 14 },
{ "replacementRequired", -1, 9 },
{ "replacementRequired", -1, 4 },
};
CString ParseParam (char **ioPos);
CSpaceObject::CSpaceObject (CUniverse &Universe) :
m_Universe(Universe),
m_pSystem(NULL),
m_iIndex(-1),
m_rBoundsX(0.0),
m_rBoundsY(0.0),
m_iHighlightCountdown(0),
m_iHighlightChar(0),
m_iDesiredHighlightChar(0),
m_pFirstEffect(NULL),
m_pOverride(NULL),
m_pFirstJoint(NULL),
m_iControlsFrozen(0),
m_iSpare(0),
m_fHookObjectDestruction(false),
m_fNoObjectDestructionNotify(false),
m_fCannotBeHit(false),
m_fSelected(false),
m_fInPOVLRS(false),
m_fCanBounce(false),
m_fIsBarrier(false),
m_fNoFriendlyFire(false),
m_fTimeStop(false),
m_fPlayerTarget(false),
m_fHasOnObjDockedEvent(false),
m_fOnCreateCalled(false),
m_fNoFriendlyTarget(false),
m_fItemEventsValid(false),
m_fHasOnDamageEvent(false),
m_fHasOnAttackedEvent(false),
m_fInDamage(false),
m_fDestroyed(false),
m_fPlayerDestination(false),
m_fShowDistanceAndBearing(false),
m_fHasInterSystemEvent(false),
m_fAutoClearDestination(false),
m_fHasOnOrdersCompletedEvent(false),
m_fPlayerDocked(false),
m_fPaintNeeded(false),
m_fNonLinearMove(false),
m_fHasName(false),
m_fAscended(false),
m_fOutOfPlaneObj(false),
m_fPainted(false),
m_fAutoClearDestinationOnDock(false),
m_fAutoClearDestinationOnDestroy(false),
m_fShowHighlight(false),
m_fShowDamageBar(false),
m_fHasGravity(false),
m_fInsideBarrier(false),
m_fHasOnSubordinateAttackedEvent(false),
m_fHasGetDockScreenEvent(false),
m_fHasOnAttackedByPlayerEvent(false),
m_fHasOnOrderChangedEvent(false),
m_fManualAnchor(false),
m_fCollisionTestNeeded(false),
m_fHasDockScreenMaybe(false),
m_fAutoClearDestinationOnGate(false),
m_f3DExtra(false),
m_fAutoCreatedPorts(false)
// CSpaceObject constructor
{
m_iDestiny = mathRandom(0, g_DestinyRange - 1);
m_dwID = Universe.CreateGlobalID();
}
CSpaceObject::~CSpaceObject (void)
// CSpaceObject destructor
{
// Can't turn this on until system destroys spaces objects
// explicitly.
#if 0
ASSERT(m_pSystem == NULL);
#endif
// Delete the list of effects
SEffectNode *pNext = m_pFirstEffect;
while (pNext)
{
SEffectNode *pDelete = pNext;
pNext = pNext->pNext;
pDelete->pPainter->Delete();
delete pDelete;
}
#ifdef DEBUG_ENEMY_CACHE_BUG
for (int i = 0; i < GetUniverse().GetSovereignCount(); i++)
GetUniverse().GetSovereign(i)->DebugObjDeleted(this);
CSystem *pSystem = GetUniverse().GetCurrentSystem();
if (pSystem)
pSystem->GetObjectGrid().DebugObjDeleted(this);
#endif
#ifdef DEBUG_OBJ_REFERENCES
// Make sure the object is not being held by anyone else
if (GetUniverse().GetPOV())
{
CSystem *pSystem = GetUniverse().GetPOV()->GetSystem();
for (int i = 0; i < pSystem->GetObjectCount(); i++)
{
CSpaceObject *pObj = pSystem->GetObject(i);
if (pObj)
{
if (pObj->m_Data.FindObjRefData(this))
ASSERT(false);
}
}
}
#endif
}
void CSpaceObject::Accelerate (const CVector &vPush, Metric rSeconds)
// Accelerate
//
// Accelerates the given object along the given vector. The magnitude of
// the vector is the force used in gigaNewtons(!). The acceleration is
// maintained for rSeconds
{
Metric rMass = GetMass();
if (rMass)
{
// rAccel needs to be in klicks per second (we assume here
// that 1 klick = 1,000 meters).
CVector rAccel = (vPush * 1000.0) / rMass;
m_vVel = m_vVel + (rAccel * rSeconds);
}
}
void CSpaceObject::AccelerateStop (Metric rPush, Metric rSeconds)
// AccelerateStop
//
// Slows down the object with the given thrust
{
Metric rMass = GetMass();
if (rMass)
{
Metric rAccel = rPush * 1000.0 / rMass;
Metric rLength;
CVector vDir = m_vVel.Normal(&rLength);
if (rAccel > rLength)
m_vVel = NullVector;
else
m_vVel = m_vVel - (vDir * rAccel);
}
}
void CSpaceObject::AddEffect (IEffectPainter *pPainter, const CVector &vPos, int iTick, int iRotation)
// AddEffect
//
// Adds an effect to the object
{
int xOffset = mathRound((vPos.GetX() - m_vPos.GetX()) / g_KlicksPerPixel);
int yOffset = mathRound((m_vPos.GetY() - vPos.GetY()) / g_KlicksPerPixel);
AddEffect(pPainter, xOffset, yOffset, iTick, iRotation);
}
void CSpaceObject::AddEffect (IEffectPainter *pPainter, int xOffset, int yOffset, int iTick, int iRotation)
// AddEffect
//
// Adds an effect to the object
{
ASSERT(pPainter->GetCreator()->IsValidUNID());
SEffectNode *pNewNode = new SEffectNode;
pNewNode->pPainter = pPainter;
pNewNode->xOffset = xOffset;
pNewNode->yOffset = yOffset;
pNewNode->iTick = iTick;
pNewNode->iRotation = iRotation;
pNewNode->pNext = m_pFirstEffect;
m_pFirstEffect = pNewNode;
}
void CSpaceObject::AddEventSubscriber (CSpaceObject *pObj)
// AddEventSubscriber
//
// Adds an object that wants to subscribe to our events
{
if (pObj
&& !pObj->IsDestroyed()
&& pObj->NotifyOthersWhenDestroyed())
m_SubscribedObjs.Add(pObj);
}
void CSpaceObject::AddEventSubscribers (const CSpaceObjectList &Objs)
// AddEventSubscribers
//
// Adds the given set of objects as subscribers to our events. We check for
// duplicates before adding.
{
for (int i = 0; i < Objs.GetCount(); i++)
{
CSpaceObject *pObj = Objs.GetObj(i);
if (!pObj->IsDestroyed()
&& pObj->NotifyOthersWhenDestroyed()
&& !FindEventSubscriber(*pObj))
m_SubscribedObjs.Add(pObj);
}
}
EnhanceItemStatus CSpaceObject::AddItemEnhancement (const CItem &itemToEnhance,
CItemType *pEnhancement,
int iLifetime,
DWORD *retdwID)
// AddItemEnhancement
//
// Adds an enhancement to the given item
{
// Select the item
CItemListManipulator ItemList(GetItemList());
if (!ItemList.SetCursorAtItem(itemToEnhance))
{
if (retdwID)
*retdwID = OBJID_NULL;
return eisNoEffect;
}
// Add the enhancement
return AddItemEnhancement(ItemList, pEnhancement, iLifetime, retdwID);
}
EnhanceItemStatus CSpaceObject::AddItemEnhancement (CItemListManipulator &ItemList,
CItemType *pEnhancement,
int iLifetime,
DWORD *retdwID)
// AddItemEnhancement
//
// Adds an enhancement to the given item
{
// Pre-init in case we exit early
if (retdwID)
*retdwID = OBJID_NULL;
// Compute expire time
int iExpireTime = (iLifetime != -1 ? GetUniverse().GetTicks() + iLifetime : -1);
// Create a new enhancement
CItemEnhancement NewEnhancement;
NewEnhancement.SetEnhancementType(pEnhancement);
NewEnhancement.SetModCode(pEnhancement->GetModCode());
NewEnhancement.SetExpireTime(iExpireTime);
// Enhance
return EnhanceItem(ItemList, NewEnhancement, retdwID);
}
void CSpaceObject::AddOverlay (COverlayType *pType, const CVector &vPos, int iRotation, int iPosZ, int iLifetime, DWORD *retdwID)
// AddOverlay
//
// Adds an overlay at the given position.
{
// Convert from a hit position to an overlay pos
int iPosAngle;
int iPosRadius;
CalcOverlayPos(pType, vPos, &iPosAngle, &iPosRadius);
// Add the overlay
AddOverlay(pType, iPosAngle, iPosRadius, iRotation, iPosZ, iLifetime, retdwID);
}
void CSpaceObject::AddOverlay (DWORD dwUNID, int iPosAngle, int iPosRadius, int iRotation, int iPosZ, int iLifetime, DWORD *retdwID)
// AddOverlay
//
// Adds an overly by UNID
{
COverlayType *pType = GetUniverse().FindOverlayType(dwUNID);
if (pType == NULL)
{
if (retdwID) *retdwID = 0;
return;
}
AddOverlay(pType, iPosAngle, iPosRadius, iRotation, iPosZ, iLifetime, retdwID);
}
ALERROR CSpaceObject::AddToSystem (CSystem &System, bool bNoGlobalInsert)
// AddToSystem
//
// Adds the object to the system
{
ALERROR error;
// We can get here with m_pSystem already set during load
ASSERT(m_pSystem == NULL || m_pSystem == &System);
// Clear the destroyed bit
m_fDestroyed = false;
// Add to system
if (error = System.AddToSystem(this, &m_iIndex))
return error;
m_pSystem = &System;
// If this is a ship or station then add to the global list
if (!bNoGlobalInsert)
System.GetUniverse().GetGlobalObjects().InsertIfTracked(this);
return NOERROR;
}
ICCItemPtr CSpaceObject::AsCCItem (CCodeChainCtx &Ctx, const CItem::SEnhanceItemResult &Result)
// AsCCItem
//
// Encode as a structure.
{
ICCItemPtr pResult(ICCItem::SymbolTable);
pResult->SetStringAt(CONSTLIT("resultCode"), CItemEnhancement::EnhanceItemStatusToString(Result.iResult));
if (!Result.Enhancement.IsEmpty())
pResult->SetStringAt(CONSTLIT("enhancement"), strPatternSubst(CONSTLIT("0x%08x"), Result.Enhancement.GetModCode()));
if (Result.Enhancement.GetID() != OBJID_NULL)
pResult->SetIntegerAt(CONSTLIT("id"), Result.Enhancement.GetID());
if (Result.Enhancement.GetExpireTime() != 0xffffffff
&& Result.Enhancement.GetExpireTime() > Ctx.GetUniverse().GetTicks())
pResult->SetIntegerAt(CONSTLIT("lifetime"), Result.Enhancement.GetExpireTime() - Ctx.GetUniverse().GetTicks());
if (!Result.sDesc.IsBlank())
pResult->SetStringAt(CONSTLIT("desc"), Result.sDesc);
return pResult;
}
void CSpaceObject::Ascend (void)
// Ascend
//
// Ascend out of system so that it can move to a different system.
{
// Set ascended flag so that when we get called at OnObjEnteredGate
// we can test for it.
SetAscended(true);
// To everyone else in the system, it looks like the object entered a gate
EnterGate(NULL, NULL_STR, NULL, true);
// Let subclasses handle this
OnAscended();
// Remove the object from the old system
Remove(ascended, CDamageSource());
}
void CSpaceObject::CalcInsideBarrier (void)
// CalcInsideBarrier
//
// Figures out if we are currently inside a barrier. If so, we set the
// m_fInsideBarrier flag.
{
int i;
if (!m_fCanBounce)
return;
// Compute the bounding rect for this object
CVector vUR, vLL;
GetBoundingRect(&vUR, &vLL);
// Loop over all other objects and see if we are inside a barrier
CSystem *pSystem = GetSystem();
for (i = 0; i < pSystem->GetObjectCount(); i++)
{
CSpaceObject *pObj = pSystem->GetObject(i);
if (pObj == NULL
|| pObj == this
|| pObj->IsDestroyed()
|| !pObj->CanBlock(this))
continue;
// Compute the bounding rect for the barrier.
CVector vBarrierUR, vBarrierLL;
pObj->GetBoundingRect(&vBarrierUR, &vBarrierLL);
// If we intersect then we're inside at least one object
if (IntersectRect(vUR, vLL, vBarrierUR, vBarrierLL)
&& pObj->ObjectInObject(pObj->GetPos(), this, GetPos()))
{
m_fInsideBarrier = true;
break;
}
}
}
void CSpaceObject::CalcOverlayPos (COverlayType *pOverlayType, const CVector &vPos, int *retiPosAngle, int *retiPosRadius)
// CalcOverlayPos
//
// Calculates an overlay position from the given absolute position.
{
Metric rRadius;
int iDirection = VectorToPolar(vPos - GetPos(), &rRadius);
int iRotationOrigin = ((pOverlayType && pOverlayType->RotatesWithSource(*this)) ? GetRotation() : 0);
if (retiPosAngle)
*retiPosAngle = AngleMod(iDirection - iRotationOrigin);
if (retiPosRadius)
*retiPosRadius = (int)(rRadius / g_KlicksPerPixel);
}
int CSpaceObject::CalcFireSolution (CSpaceObject *pTarget, Metric rMissileSpeed) const
// CalcFireSolution
//
// Returns the angle to aim at to hit the given target. Or -1 if the target cannot be
// intercepted.
{
CVector vPos = pTarget->GetPos() - GetPos();
CVector vVel = pTarget->GetVel() - GetVel();
Metric rTimeToIntercept = CalcInterceptTime(vPos, vVel, rMissileSpeed);
if (rTimeToIntercept < 0.0)
return -1;
// Compute the intercept point and then the direction
CVector vInterceptPoint = vPos + vVel * rTimeToIntercept;
return VectorToPolar(vInterceptPoint);
}
int CSpaceObject::CalcMiningDifficulty (EAsteroidType iType) const
// CalcMiningDifficulty
//
// Compute mining difficult based on asteroid (0-100).
{
ICCItemPtr pValue = GetTypeProperty(CCodeChainCtx(GetUniverse()), PROPERTY_CORE_MINING_DIFFICULTY);
if (!pValue->IsNil())
return Max(0, Min(pValue->GetIntegerValue(), 100));
return CAsteroidDesc::GetDefaultMiningDifficulty(iType);
}
DWORD CSpaceObject::CalcSRSVisibility (SViewportPaintCtx &Ctx) const
// CalcSRSVisibility
//
// Calculates the SRS opacity to paint with.
//
// 0 = Fully visible.
// 1-255 = varying degrees of visibility (1 = lowest, 255 = highest).
{
int iRangeIndex = GetDetectionRangeIndex(Ctx.iPerception);
if (iRangeIndex < 6 || Ctx.pCenter == NULL || Ctx.pCenter == this)
return 0;
Metric rRange = CPerceptionCalc::GetRange(iRangeIndex);
Metric rDist = Ctx.pCenter->GetDistance(this);
if (rDist <= rRange)
return 0;
return 255 - Min(254, (int)((rDist - rRange) / g_KlicksPerPixel) * 2);
}
CSpaceObject *CSpaceObject::CalcTargetToAttack (CSpaceObject *pAttacker, CSpaceObject *pOrderGiver)
// CalcTargetToAttack
//
// Figure out whether to attack the order giver or not. NOTE: We return NULL if
// neither can be attacked.
{
CPerceptionCalc Perception(GetPerception());
// Figure out if we can see the attacker
Metric rAttackerDist2 = g_InfiniteDistance;
bool bCanSeeAttacker = false;
if (pAttacker)
{
rAttackerDist2 = GetDistance2(pAttacker);
if (Perception.CanBeTargeted(pAttacker, rAttackerDist2))
bCanSeeAttacker = true;
}
// Figure out if we can see the order giver
Metric rOrderGiverDist2 = g_InfiniteDistance;
bool bCanSeeOrderGiver = false;
if (pOrderGiver == pAttacker)
{
bCanSeeOrderGiver = bCanSeeAttacker;
rOrderGiverDist2 = rAttackerDist2;
}
else if (pOrderGiver)
{
rOrderGiverDist2 = GetDistance2(pOrderGiver);
if (Perception.CanBeTargeted(pOrderGiver, rOrderGiverDist2))
bCanSeeOrderGiver = true;
}
// Choose whichever is valid and visible.
if (pAttacker == pOrderGiver)
return (bCanSeeAttacker ? pAttacker : NULL);
else if (pAttacker == NULL || !bCanSeeAttacker)
return (bCanSeeOrderGiver ? pOrderGiver : NULL);
else if (pOrderGiver == NULL || !bCanSeeOrderGiver)
return (bCanSeeAttacker ? pAttacker : NULL);
// Both attacker and order giver are valid and visible to us. If one is
// twice as close to us, we pick that one.
else if (rAttackerDist2 < rOrderGiverDist2 * 4.0)
return pAttacker;
else if (rOrderGiverDist2 < rAttackerDist2 * 4.0)
return pOrderGiver;
// Otherwise, we pick randomly, weighing the order giver a little more.
else if (mathRandom(1, 100) <= 60)
return pOrderGiver;
else
return pAttacker;
}
Metric CSpaceObject::CalculateItemMass (Metric *retrCargoMass) const
// CalculateCargoMass
//
// Returns the total mass of the items
{
int i;
Metric rTotal = 0.0;
Metric rTotalCargo = 0.0;
for (i = 0; i < m_ItemList.GetCount(); i++)
{
const CItem &Item = m_ItemList.GetItem(i);
Metric rMass = Item.GetMass() * Item.GetCount();
// All items count towards item mass
rTotal += rMass;
// Only uninstalled items count in cargo space
if (!Item.IsInstalled())
rTotalCargo += rMass;
}
if (retrCargoMass)
*retrCargoMass = rTotalCargo;
return rTotal;
}
bool CSpaceObject::CanCommunicateWith (CSpaceObject *pSender)
// CanCommunicateWith
//
// Returns TRUE if this object can receive communications from pSender
{
int i;
// We can't communicate if we don't have a handler
CCommunicationsHandler *pHandler = GetCommsHandler();
if (pHandler == NULL)
return false;
// We can't communicate if we don't know about the object
if (!IsKnown())
return false;
// We can't communicate if we're suspended, etc. (But it's OK if we're
// virtual.)
if (IsUnreal())
return false;
// Can't communicate if we're part of a different object
if (IsAttached())
return false;
// We can't communicate if we are out of range
if ((pSender->GetPos() - m_vPos).Length2() > g_rMaxCommsRange2)
return false;
// See if any of the messages are valid. If at least
// one is, then we can communicate.
for (i = 0; i < pHandler->GetCount(); i++)
{
if (pHandler->GetMessage(i).OnShowEvent.pCode == NULL)
return true;
else
{
CCodeChainCtx Ctx(GetUniverse());
// Define parameters
Ctx.DefineContainingType(this);
Ctx.SaveAndDefineSourceVar(this);
Ctx.DefineSpaceObject(CONSTLIT("gSender"), pSender);
// Execute
bool bShow;
ICCItem *pResult = Ctx.Run(pHandler->GetMessage(i).OnShowEvent);
if (pResult->IsNil())
bShow = false;
else if (pResult->IsError())
{
pSender->SendMessage(this, pResult->GetStringValue());
bShow = false;
}
else
bShow = true;
Ctx.Discard(pResult);
if (bShow)
return bShow;
}
}
return false;
}
bool CSpaceObject::CanDetect (int iPerception, CSpaceObject *pObj)
// CanDetect
//
// Returns TRUE if this object (with given perception) can detect the target
{
CVector vDist = pObj->GetPos() - GetPos();
return (vDist.Length2() < pObj->GetDetectionRange2(iPerception));
}
CItem::SEnhanceItemResult CSpaceObject::CanEnhanceItem (CItemListManipulator &ItemList, const CItem &EnhancementItem, CString *retsError) const
// CanEnhanceItem
//
// Returns an SEnhanceItemResult structure. If the result is eisUnknown, then
// we got an error trying to enhance.
{
ASSERT(ItemList.IsCursorValid());
ASSERT(!EnhancementItem.IsEmpty());
DEBUG_TRY
const CItem &TargetItem = ItemList.GetItemAtCursor();
// See if we have an explicit event
CItem::SEnhanceItemResult Result;
if (!EnhancementItem.FireCanEnhanceItem(*this, TargetItem, Result, retsError))
{
Result.iResult = eisUnknown;
return Result;
}
// If <CanEnhanceItem> worked, then we're done.
if (Result.iResult != eisUnknown)
return Result;
// Get the enhancement to confer
if (!EnhancementItem.GetEnhancementConferred(*this, TargetItem, Result, retsError))
{
Result.iResult = eisUnknown;
return Result;
}
// If no mod, nothing to do (but Result.sDesc might explain what happened).
if (Result.Enhancement.IsEmpty())
{
Result.iResult = eisNoEffect;
return Result;
}
// Figure out the effect of the enhancement on the item
else
{
CItemEnhancement OldEnhancement = TargetItem.GetMods();
Result.iResult = OldEnhancement.Combine(TargetItem, Result.Enhancement);
// Done
return Result;
}
DEBUG_CATCH
}
bool CSpaceObject::CanFireOnObjHelper (CSpaceObject *pObj) const
// CanFireOnObjHelper
//
// Return TRUE if a missile fired by this object can hit the given object
{
return (
// We cannot hit our friends (if our source can't)
(CanHitFriends() && pObj->CanBeHitByFriends()) || GetSovereign() == NULL || !GetSovereign()->IsFriend(pObj->GetSovereign())
);
}
bool CSpaceObject::CanInstallItem (const CItem &Item, int iSlot, InstallItemResults *retiResult, CString *retsResult, CItem *retItemToReplace)
// CanInstallItem
//
// Must be overridden by subclasses.
{
if (retiResult)
*retiResult = insCannotInstall;
if (retsResult)
*retsResult = CONSTLIT("Item installation not supported.");
return false;
}
void CSpaceObject::ClearCondition (CConditionSet::ETypes iCondition, DWORD dwFlags)
// ClearCondition
//
// Clears the given condition (generically).
{
switch (iCondition)
{
case CConditionSet::cndTimeStopped:
m_fTimeStop = false;
break;
default:
OnClearCondition(iCondition, dwFlags);
break;
}
}
void CSpaceObject::CommsMessageFrom (CSpaceObject *pSender, int iIndex)
// CommsMessageFrom
//
// Handle comms message from the sender
{
CCommunicationsHandler *pHandler = GetCommsHandler();
ASSERT(pHandler && iIndex < pHandler->GetCount());
const CCommunicationsHandler::SMessage &Msg = pHandler->GetMessage(iIndex);
if (Msg.InvokeEvent.pCode)
{