-
Notifications
You must be signed in to change notification settings - Fork 3
Class By Class Code Breakdown
The HeartData
class contains various static properties and fields used throughout the mod. Some notable members include:
-
HeartNetworkId
: The ID used for network communication. -
IsLoaded
,IsSuspended
,IsPaused
: Flags indicating the current state of the mod. -
Net
: An instance of theHeartNetwork
class for network communication. -
Log
: An instance of theHeartLog
class for logging. -
SyncRange
,SyncRangeSq
: The synchronization range and its square value. -
Random
: An instance of theRandom
class for random number generation. -
SteamId
: The Steam ID of the current player. -
Players
: A list ofIMyPlayer
objects representing the connected players. -
DegradedMode
: A flag indicating if the mod is in degraded mode. -
OnGridAdd
,OnGridRemove
: Actions invoked when a grid is added or removed.
The HeartLoad
class is responsible for loading and unloading the mod. It inherits from MySessionComponentBase
and is marked with the MySessionComponentDescriptor
attribute. Some key methods and properties include:
-
LoadData()
: Loads the mod and initializes various components such asHeartData
,HeartNetwork
,WeaponDefinitionManager
,ProjectileDefinitionManager
,DefinitionReciever
,ApiSender
, andCommandHandler
. -
UpdateAfterSimulation()
: Updates the mod after each simulation step. It handles loading, entity addition/removal, network updates, and degraded mode. -
UpdatingStopped()
: Called when the mod update is stopped. -
UnloadData()
: Unloads the mod and cleans up resources.
The HeartUtils
class provides utility methods for various purposes. Some notable methods include:
-
GetRelationsBetweenPlayers()
: Determines the relationship between two players based on their factions. -
GetGridOwner()
: Retrieves the owner of a grid. -
GetPlayerFromSteamId()
: Retrieves the player with a specific Steam ID. -
MapPlayerRelationsToBlock()
: Maps player relations to block relations. -
GetRelationsBetweeenGrids()
: Determines the relationship between two grids based on their owners. -
GetRelationsBetweenGridAndPlayer()
: Determines the relationship between a grid and a player. -
Clamp()
,ClampAbs()
,MinAbs()
,MaxAbs()
: Various clamping and absolute value utility methods. -
LimitRotationSpeed()
: Limits the rotation speed between two angles. -
NormalizeAngle()
: Normalizes an angle to a specific range.
The DebugDraw
class is used for drawing debug information in the game world. It is marked with the MySessionComponentDescriptor
attribute. Some key methods include:
-
AddPoint()
,AddGridPoint()
: Adds a debug point at a specific position. -
AddGPS()
,AddGridGPS()
: Adds a GPS marker at a specific position. -
AddLine()
: Adds a debug line between two positions. -
Draw()
: Draws the queued debug points, grid points, and lines.
The DefinitionReciever
class is responsible for receiving and handling definitions. It listens for a specific message ID and handles the received definitions. Some key methods include:
-
LoadData()
: Registers the message handler and sends a request for definitions. -
RecieveDefinitions()
: Receives and processes the definitions. -
UnloadData()
: Unregisters the message handler.
The ApiSender
class is responsible for sending and receiving API methods between the mod and other scripts or mods. Some key methods include:
-
LoadData()
: Sends the available API methods to other scripts or mods and registers a message handler to receive API method requests. -
UnloadData()
: Unregisters the message handler. -
RecieveApiMethods()
: Handles the received API method requests and sends the available API methods if requested.
The HeartApiMethods
class contains the implementation of various API methods provided by the mod. These methods are categorized into different regions:
-
AddOnSpawn()
,AddOnImpact()
,AddOnEndOfLife()
: Adds event handlers to a specific projectile definition. -
GetProjectileDefinitionId()
,GetProjectileDefinition()
: Retrieves the ID or serialized definition of a projectile definition. -
RegisterProjectileDefinition()
,UpdateProjectileDefinition()
,RemoveProjectileDefinition()
: Registers, updates, or removes a projectile definition. -
SpawnProjectile()
: Spawns a projectile with the specified parameters. -
GetProjectileInfo()
: Retrieves information about a specific projectile.
-
HasWeapon()
: Checks if a block has a weapon attached to it. -
SubtypeHasDefinition()
: Checks if a subtype has a weapon definition. -
GetWeaponDefinitions()
,GetWeaponDefinition()
: Retrieves all weapon definitions or a specific weapon definition. -
RegisterWeaponDefinition()
,UpdateWeaponDefinition()
,RemoveWeaponDefinition()
: Registers, updates, or removes a weapon definition.
-
LogWriteLine()
: Writes a line to the log. -
GetNetworkLoad()
: Retrieves the current network load. -
AddChatCommand()
: Adds a chat command.
The DefinitionContainer
class is a serializable class used to store and transfer weapon and ammo definitions. It contains arrays of serialized weapon and ammo definitions.
The code defines two enums:
-
IFF_Enum
: Represents the identification friend or foe (IFF) options for targeting. -
TargetType_Enum
: Represents the types of entities that can be targeted.
The CriticalHandle
class handles critical exceptions and initiates a shutdown of the mod if a critical exception occurs. Some key methods include:
-
LoadData()
,UnloadData()
: Loads and unloads the critical handle. -
Update()
: Updates the critical handle and initiates the shutdown if a critical exception has occurred. -
ThrowCriticalException()
: Throws a critical exception and initiates the shutdown process.
The HeartLog
class provides logging functionality for the mod. It allows writing log messages and exceptions to a file. Some key methods include:
-
Log()
: Writes a log message. -
LogException()
: Logs an exception. -
Close()
: Closes the log file.
The n_SerializableError
class is a serializable class used to transfer error information over the network. It contains the exception message, stack trace, and a flag indicating if it is a critical error.
The SoftHandle
class handles non-critical exceptions and raises them as soft exceptions. It provides methods to raise exceptions with different parameters and sends the exceptions to clients if the server raises them.
The HeartNetwork
class handles network communication for the mod. It provides methods for sending and receiving packets, updating time offsets, and managing network load. Some key methods include:
-
LoadData()
,UnloadData()
: Loads and unloads the network component. -
Update()
: Updates the network component and calculates network load. -
SendToPlayer()
,SendToEveryone()
,SendToEveryoneInSync()
,SendToServer()
: Sends packets to specific players, all players, players within sync range, or the server. -
HighestNetworkLoad()
: Retrieves the type with the highest network load.
The n_TimeSyncPacket
class is a packet used for synchronizing time between the server and clients. It contains timestamps for outgoing and incoming packets and calculates the time offset between the server and client.
The Projectile
class represents a projectile in the game. It contains properties and methods for managing the projectile's state, behavior, and appearance. Some key properties and methods include:
-
Definition
: The projectile's definition. -
Position
,Direction
,Velocity
: The projectile's position, direction, and velocity. -
Firer
: The entity that fired the projectile. -
Guidance
: The projectile's guidance system. -
TickUpdate()
: Updates the projectile's state and behavior. -
CheckHits()
: Checks for collisions and applies damage. -
AsSerializable()
: Converts the projectile to a serializable format for network transmission. -
InitEffects()
,DrawUpdate()
,UpdateAudio()
: Initializes and updates the projectile's visual and audio effects.
The ProjectileDefinitionManager
class manages the projectile definitions used by the mod. It provides methods for registering, retrieving, replacing, and removing projectile definitions. Some key methods include:
-
GetDefinition()
,GetSerializedDefinition()
: Retrieves a projectile definition or its serialized form. -
GetId()
: Retrieves the ID of a projectile definition. -
HasDefinition()
: Checks if a projectile definition exists. -
RegisterDefinition()
,ReplaceDefinition()
,RemoveDefinition()
: Registers, replaces, or removes a projectile definition. -
ClearDefinitions()
: Clears all projectile definitions.
The DamageHandler
class handles damage events for projectiles. It processes damage events for different entity types and applies damage and impulses accordingly. Some key methods include:
-
QueueEvent()
: Queues a damage event for processing. -
Update()
: Processes the queued damage events. -
GetCollider()
: Retrieves the block that collides with a raycast.
The DamageEvent
class represents a damage event caused by a projectile. It contains information about the entities involved, hit positions, and the projectile that caused the damage.
The ProjectileGuidance
class represents the guidance system for a projectile. It manages the targeting and steering of the projectile based on the guidance stages defined in the projectile's definition. Some key methods include:
-
RunGuidance()
: Runs the guidance logic for the current stage. -
NextStage()
: Transitions to the next guidance stage. -
StepDirection()
: Calculates the new direction for the projectile based on the target and guidance parameters. -
CheckRaycast()
,PreformRaycast()
: Performs raycasts to find potential targets. -
IsTargetAllowed()
: Checks if a target is allowed based on the IFF settings.
The ProjectileManager
class manages the active projectiles in the game. It updates and synchronizes the projectiles across the network. Some key methods include:
-
LoadData()
,UnloadData()
: Loads and unloads the projectile manager. -
UpdateAfterSimulation()
,UpdatingStopped()
,Draw()
: Updates and draws the projectiles. -
AddProjectile()
: Adds a new projectile to the manager. -
GetProjectile()
: Retrieves a projectile by its ID. -
GetProjectilesInSphere()
: Retrieves projectiles within a specified sphere.
The ProjectileDefinitionManager
class manages the projectile definitions used by the mod. It provides methods for registering, retrieving, replacing, and removing projectile definitions. Some key methods include:
-
GetDefinition()
,GetSerializedDefinition()
: Retrieves a projectile definition or its serialized form. -
GetId()
: Retrieves the ID of a projectile definition. -
HasDefinition()
: Checks if a projectile definition exists. -
RegisterDefinition()
,ReplaceDefinition()
,RemoveDefinition()
: Registers, replaces, or removes a projectile definition. -
ClearDefinitions()
: Clears all projectile definitions.
The ProjectileNetwork
class handles the network synchronization of projectiles. It manages the synchronization streams for different players and provides methods for queueing and receiving projectile updates. Some key methods include:
-
QueueSync_PP()
,QueueSync_FireEvent()
: Queues projectile updates for synchronization. -
Recieve_PP()
,Recieve_FireEvent()
: Receives and processes projectile updates from the network.
Handles serialization and deserialization of projectile information for networking.
-
public n_SerializableProjectileInfos(uint[], Vector3[], Vector3[], int[], long[] = null, long?[] = null, uint[] = null)
- Initializes a new instance.
-
public Vector3[] PlayerRelativePosition()
- Returns array of player-relative positions.
-
public Vector3 PlayerRelativePosition(int)
- Returns player-relative position at index.
-
public Vector3[] Direction()
- Returns array of projectile directions.
-
public Vector3 Direction(int)
- Returns projectile direction at index.
-
public Projectile ToProjectile(int)
- Converts to Projectile object.
-
public override void Received(ulong)
- Handles received data.
public uint[] UniqueProjectileId
public int[] DefinitionId
public int MillisecondsFromMidnight
public long[] FirerEntityId
public long?[] TargetEntityId
public uint[] ProjectileAge
Handles serialization and deserialization of fire events for projectiles.
-
public n_SerializableFireEvents(List<Projectile>)
- Initializes a new instance.
-
public Vector3[] Direction()
- Returns array of projectile directions.
-
public Vector3 Direction(int)
- Returns projectile direction at index.
-
public Projectile ToProjectile(int)
- Converts to Projectile object.
-
public override void Received(ulong)
- Handles received data.
public long[] FirerEntityId
public uint[] UniqueProjectileId
public int MillisecondsFromMidnight
Manages synchronization of projectiles and fire events among players.
-
public void QueueSync_PP(Projectile, int = 0)
- Queues projectile synchronization for all players.
-
public void QueueSync_PP(IMyPlayer, Projectile, int = 0)
- Queues projectile synchronization for a specific player.
-
public void QueueSync_FireEvent(Projectile)
- Queues fire event synchronization for all players.
-
public void QueueSync_FireEvent(IMyPlayer, Projectile)
- Queues fire event synchronization for a specific player.
-
public void Update1()
- Updates projectile synchronization.
-
public void Init()
- Initializes the projectile network.
-
public void Close()
- Closes the projectile network.
Handles serialization and deserialization of projectile arrays.
-
public n_ProjectileArray(List<n_SerializableProjectile>)
- Initializes a new instance with a list of projectiles.
-
public n_ProjectileArray(n_SerializableProjectile[])
- Initializes a new instance with an array of projectiles.
-
public override void Received(ulong)
- Handles received data.
Handles requests for specific projectiles.
-
public n_ProjectileRequest(uint)
- Initializes a new instance with a projectile ID.
-
public override void Received(ulong)
- Handles received data.
-
Fields:
-
IsActive
: Nullable boolean, defaults to true. -
Id
: Unsigned integer. -
TimestampFromMidnight
: Unsigned integer. -
DefinitionId
: Nullable integer. -
Position
: Nullable Vector3D. -
Direction
: Nullable Vector3. -
InheritedVelocity
: Nullable Vector3. -
Velocity
: Nullable float. -
Firer
: Nullable long.
-
-
Methods:
-
Received(ulong SenderSteamId)
: Overrides base method. If not server, updates projectile sync.
-
-
Fields:
-
Name
: String, defaults to empty. -
Ungrouped
: Ungrouped struct. -
Damage
: Damage struct. -
PhysicalProjectile
: PhysicalProjectile struct. -
Visual
: Visual struct. -
Audio
: Audio struct. -
Guidance
: Array of Guidance, initialized to empty array. -
Networking
: Networking struct. -
LiveMethods
: LiveMethods instance.
-
-
Fields:
-
ReloadPowerUsage
: Float. -
Recoil
: Integer. -
Impulse
: Integer. -
ShotsPerMagazine
: Integer. -
MagazineItemToConsume
: String. -
SyncPriority
: Unsigned short.
-
-
Fields:
-
NetworkingMode
: NetworkingModeEnum. -
DoConstantSync
: Boolean. -
NetworkPriority
: Unsigned short.
-
-
Fields:
- Various float and integer fields for damage calculation.
-
Fields:
- Various float fields related to physical properties of the projectile.
-
Fields:
- Various fields related to visual representation of the projectile.
-
Fields:
- Various fields related to audio representation of the projectile.
-
Fields:
- Various fields related to guidance mechanisms of the projectile.
-
Fields:
-
OnSpawn
: Action. -
OnImpact
: Action. -
OnEndOfLife
: Action.
-
-
Fields:
- Various fields related to PID control.
-
Fields:
-
_weaponDefinition
: WeaponDefinitionBase instance. -
_weaponLogic
: SorterWeaponLogic instance. -
_resources
: Dictionary<string, float>.
-
-
Constructor:
-
WeaponResourceSystem(WeaponDefinitionBase weaponDefinition, SorterWeaponLogic weaponLogic)
: Initializes the resource system.
-
-
Methods:
-
CanShoot()
: Returns true if resources are sufficient to shoot. -
ConsumeResources()
: Consumes resources based on the weapon definition. -
RegenerateResources(float deltaTime)
: Regenerates resources over time. -
Update(float deltaTime)
: Updates resource system. -
Unload()
: Unloads resources.
-
-
Private Methods:
-
ShowResourceStatus()
: Displays resource status. -
ShowNotification(string message, int duration)
: Displays notification.
-
-
Fields:
-
controlledGrid
: IMyCubeGrid. -
Visible
: Boolean, defaults to true.
-
-
Methods:
-
UpdateAfterSimulation()
: Overrides base method. Updates visibility based on current screen. -
PerWeaponUpdate(SorterWeaponLogic weapon)
: Abstract method for per-weapon updates.
-
-
Fields:
-
_hasInitedHud
: Boolean. -
_window
: ResourceStatusWindow.
-
-
Methods:
-
UpdateAfterSimulation()
: Overrides base method. Updates resource information. -
InitHud()
: Initializes HUD. -
GetResourceCount()
: Gets resource count.
-
-
Constants:
-
MaxVisibleIndicators
: Integer.
-
-
Fields:
-
FixedMaterial
: MyStringId. -
FixedColor
: Vector4. -
TurretMaterial
: MyStringId. -
TurretColor
: Vector4. -
viewDist
: Float. -
numVisible
: Integer.
-
-
Methods:
-
LoadData()
: Loads data. -
UpdateAfterSimulation()
: Overrides base method. Updates number of visible indicators. -
PerWeaponUpdate(SorterWeaponLogic weapon)
: Overrides abstract method.
-
-
Fields:
-
HasInitedHud
: Boolean. -
Window
: ReloadWindow.
-
-
Methods:
-
Init(MyObjectBuilder_SessionComponent sessionComponent)
: Overrides base method. Initializes HUD. -
Draw()
: Overrides base method. Draws reload indicators. -
PerWeaponUpdate(SorterWeaponLogic weapon)
: Overrides abstract method.
-
-
Fields:
-
debugInfo
: Label. -
debugInfo2
: Label. -
weaponStatus
: ListBox.
-
-
Methods:
-
UpdateDebugText(int numProjectiles, int numWeapons, int networkLoad)
: Updates debug text. -
UpdateWeaponText(SorterWeaponLogic weapon)
: Updates weapon text. -
GetEntry(uint id)
: Gets entry from weapon status. -
UpdateWeaponText(List<SorterWeaponLogic> weapons)
: Updates weapon text for list of weapons. -
ClearWeaponText()
: Clears weapon text.
-
-
Fields:
-
commands
: Dictionary<string, Command>.
-
-
Methods:
-
ShowHelp()
: Shows command help. -
FillGridWeapons()
: Fills magazines on the current grid. -
ReloadGridWeapons()
: Forces reload of weapons on the current grid. -
Init()
: Initializes command handler. -
Command_MessageEnteredSender(ulong sender, string messageText, ref bool sendToOthers)
: Handles chat commands. -
Close()
: Closes command handler. -
AddCommand(string command, string helpText, Action<string[]> action, string modName = "HeartMod")
: Adds a command.
-
-
Constants:
-
TickRate
: Float.
-
-
Fields:
-
TrailFade
: List of LineFade.
-
-
Methods:
-
AddLine(Vector3D start, Vector3D end, float fadeTime, float width, Vector4 color, MyStringId texture)
: Adds a line to fade. -
UpdateTrailFade(float delta)
: Updates trail fade.
-
-
Fields:
-
_resourceInfo
: Label.
-
-
Methods:
-
ResourceStatusWindow(HudParentBase parent)
: Constructor. -
UpdateResourceInfo(string infoText)
: Updates resource information.
-
-
Fields:
-
Start
: Vector3D. -
End
: Vector3D. -
RemainingTime
: Float. -
FadeTime
: Float. -
Length
: Double. -
Color
: Vector4. -
Width
: Float. -
Texture
: MyStringId.
-
-
Methods:
-
LineFade(Vector3D start, Vector3D end, float fadeTime, float width, Vector4 color, MyStringId texture)
: Constructor.
-
GuiBlockCategoryHelper Class
This class assists in managing GUI block categories. It provides functionality to create and add blocks to a category.
Fields:
category: Stores the GUI block category definition.
Methods:
GuiBlockCategoryHelper(string Name, string Id): Constructor method to create a new GUI block category definition.
AddBlock(string subtypeId): Adds a block to the GUI block category.
PID Class
This class implements a Proportional-Integral-Derivative (PID) controller for single-variable systems.
Fields:
kIntegral: Proportional constant.
kDerivative: Integral constant.
kProportional: Derivative constant.
p_error: Previous error value.
p_integral: Integral of error values.
Methods:
PID(): Default constructor.
PID(double kProportional, double kIntegral, double kDerivative): Constructor with PID constants.
Tick(double current, double desired, double bias, double delta): Computes the control signal for the PID controller.
VectorPID Class
This class extends PID control to vector systems, providing control for each component separately.
Fields:
x, y, z: PID controllers for each component.
Methods:
VectorPID(double kProportional, double kIntegral, double kDerivative): Constructor with PID constants.
Tick(Vector3D current, Vector3D desired, Vector3D bias, double delta): Computes the control signal for each component of the vector system.
PriorityQueue Class
This class implements a priority queue data structure using a sorted dictionary.
Fields:
dictionary: Sorted dictionary to store elements based on priority.
selector: Function to extract priority from elements.
Methods:
PriorityQueue(Func<TElement, TKey> selector): Constructor with a selector function.
Enqueue(TElement item): Adds an element to the priority queue.
Dequeue(): Removes and returns the element with the highest priority.
SubpartManager Class
This class manages subparts of entities, providing methods to retrieve and manipulate them.
Fields:
CachedSubparts: Dictionary to cache subparts of entities.
Methods:
GetSubpart(IMyEntity entity, string name): Retrieves a subpart by name for a given entity.
RecursiveGetSubpart(IMyEntity entity, string name): Retrieves a subpart recursively by name for a given entity.
GetAllSubparts(IMyEntity entity): Retrieves all subpart names for a given entity.
LocalRotateSubpart(MyEntitySubpart subpart, Matrix matrix): Rotates a subpart locally.
LocalRotateSubpartAbs(MyEntitySubpart subpart, Matrix matrix): Rotates a subpart absolutely.
TargetingHelper Class
This static class provides helper methods for targeting, including interception point calculations.
Methods:
InterceptionPoint(Vector3D startPos, Vector3D startVel, Projectile target, int projectileDef): Calculates the interception point between a projectile and a moving target.
InterceptionPoint(Vector3D startPos, Vector3D startVel, IMyEntity target, int projectileDef): Calculates the interception point between a projectile and a stationary target.
InterceptionPoint(Vector3D startPos, Vector3D startVel, Vector3D targetPos, Vector3D targetVel, float projectileSpeed): Calculates the interception point between a projectile and a moving target.
TimeOfInterception(Vector3 relativePosition, Vector3 relativeVelocity, float projectileSpeed): Calculates the time until interception between a projectile and a moving target.
Class: SorterTurretLogic Description:
This class represents the logic for a turret controlled by a conveyor sorter.
It handles aiming, shooting, and target acquisition for the turret.
Properties:
Azimuth: Current azimuth angle of the turret.
Elevation: Current elevation angle of the turret.
DesiredAzimuth: Desired azimuth angle of the turret.
DesiredElevation: Desired elevation angle of the turret.
IsTargetAligned: Indicates whether the turret is aligned with its target.
IsTargetInRange: Indicates whether the target is within range of the turret.
AimPoint: The point in 3D space that the turret is aiming at.
TargetAge: The age of the current target.
TargetEntity: The entity that the turret is targeting.
TargetProjectile: The projectile that the turret is targeting.
Methods:
UpdateAfterSimulation(): Updates the targeting and shooting logic after the simulation.
TryShoot(): Attempts to shoot if conditions are met.
CalcMuzzleMatrix(int id, bool local = false): Calculates the muzzle matrix for the specified muzzle ID.
UpdateAzimuthElevation(Vector3D aimpoint): Updates the turret's azimuth and elevation angles based on the aim point.
UpdateTurretSubparts(float delta): Updates the rotation of turret subparts based on the desired azimuth and elevation.
SetFacing(float azimuth, float elevation): Sets the desired azimuth and elevation angles of the turret.
IncreaseAIRange(): Increases the AI range of the turret.
DecreaseAIRange(): Decreases the AI range of the turret.
LoadDefaultSettings(): Loads default settings for the turret.
LoadSettings(): Loads settings for the turret from storage.
ShouldConsiderTarget(IMyCubeGrid targetGrid): Checks if the turret should consider targeting the specified cube grid.
ShouldConsiderTarget(IMyCharacter targetCharacter): Checks if the turret should consider targeting the specified character.
ShouldConsiderTarget(Projectile targetProjectile): Checks if the turret should consider targeting the specified projectile.
ShouldConsiderTarget(MyRelationsBetweenPlayerAndBlock relations): Checks if the turret should consider targeting based on player-block relations.