diff --git a/Spark Engine/Source/Audio/AudioEngine.h b/Spark Engine/Source/Audio/AudioEngine.h index 8bdc52bc6..3c5f6e76c 100644 --- a/Spark Engine/Source/Audio/AudioEngine.h +++ b/Spark Engine/Source/Audio/AudioEngine.h @@ -1,4 +1,15 @@ -// AudioEngine.h +/** + * @file AudioEngine.h + * @brief XAudio2-based audio engine with 3D spatial audio support + * @author Spark Engine Team + * @date 2025 + * + * This class provides a comprehensive audio system built on XAudio2, supporting + * both 2D and 3D audio playback, sound effect management, volume controls, and + * an object pool system for efficient audio source management. The engine handles + * loading, playing, and managing multiple simultaneous audio sources. + */ + #pragma once #include "Utils/Assert.h" @@ -13,18 +24,30 @@ using DirectX::XMFLOAT3; using DirectX::XMMATRIX; +/** + * @brief Audio source structure for managing individual sound instances + * + * Represents a single audio source that can play a sound effect with specific + * properties like position, velocity, volume, and pitch. Used for both 2D + * and 3D audio playback within the audio engine's object pool system. + */ struct AudioSource { - IXAudio2SourceVoice* Voice; - XMFLOAT3 Position; - XMFLOAT3 Velocity; - float Volume; - float Pitch; - bool Is3D; - bool IsLooping; - bool IsPlaying; - SoundEffect* Sound; + IXAudio2SourceVoice* Voice; ///< XAudio2 source voice for audio playback + XMFLOAT3 Position; ///< 3D world position for spatial audio + XMFLOAT3 Velocity; ///< 3D velocity for Doppler effects + float Volume; ///< Volume level (0.0 to 1.0+) + float Pitch; ///< Pitch multiplier (1.0 = normal pitch) + bool Is3D; ///< Whether this source uses 3D positioning + bool IsLooping; ///< Whether the sound should loop continuously + bool IsPlaying; ///< Whether the source is currently playing + SoundEffect* Sound; ///< Pointer to the associated sound effect + /** + * @brief Default constructor with safe initial values + * + * Initializes all members to safe defaults suitable for audio playback. + */ AudioSource() : Voice(nullptr) , Position(0, 0, 0) @@ -39,48 +62,255 @@ struct AudioSource } }; +/** + * @brief Main audio engine class providing comprehensive audio functionality + * + * The AudioEngine class manages all audio operations for the Spark Engine using + * XAudio2 as the underlying audio API. It provides sound loading, 3D spatial audio, + * volume controls, and efficient audio source management through object pooling. + * + * Features include: + * - XAudio2-based audio playback with hardware acceleration + * - 2D and 3D spatial audio positioning + * - Sound effect loading and management + * - Volume controls (master, SFX, music) + * - Audio source pooling for performance + * - Looping and one-shot audio playback + * - Pitch and volume controls per source + * + * @note The engine uses an object pool to efficiently reuse audio sources + * @warning Initialize() must be called before any audio operations + */ class AudioEngine { public: + /** + * @brief Default constructor + * + * Initializes member variables to safe default values. Call Initialize() + * to set up the XAudio2 system. + */ AudioEngine(); + + /** + * @brief Destructor + * + * Automatically calls Shutdown() to ensure proper cleanup of all + * XAudio2 resources and audio sources. + */ ~AudioEngine(); + /** + * @brief Initialize the audio engine with XAudio2 + * + * Sets up the XAudio2 engine, creates the mastering voice, and initializes + * the audio source object pool with the specified number of sources. + * + * @param maxSources Maximum number of simultaneous audio sources + * @return HRESULT indicating success or failure of audio initialization + * @note A typical value for maxSources is 32-64 for most games + */ HRESULT Initialize(size_t maxSources); + + /** + * @brief Update the audio engine for the current frame + * + * Updates all active audio sources, processes 3D audio calculations, + * and manages the audio source pool. Should be called once per frame. + * + * @param deltaTime Time elapsed since last frame in seconds + */ void Update(float deltaTime); + + /** + * @brief Shutdown the audio engine and clean up resources + * + * Stops all playing sounds, releases all XAudio2 resources, and cleans + * up the audio source pool. Safe to call multiple times. + */ void Shutdown(); + /** + * @brief Load a sound effect from file + * + * Loads an audio file and associates it with a name for later playback. + * Supports common audio formats like WAV files. + * + * @param name Unique name to identify the sound effect + * @param filename Path to the audio file to load + * @return HRESULT indicating success or failure of sound loading + */ HRESULT LoadSound(const std::string& name, const std::wstring& filename); + + /** + * @brief Unload a previously loaded sound effect + * + * Removes a sound effect from memory and stops any instances currently + * playing that sound. + * + * @param name Name of the sound effect to unload + */ void UnloadSound(const std::string& name); + + /** + * @brief Get a pointer to a loaded sound effect + * + * Retrieves a sound effect by name for direct manipulation or inspection. + * + * @param name Name of the sound effect to retrieve + * @return Pointer to the SoundEffect, or nullptr if not found + */ SoundEffect* GetSound(const std::string& name); + /** + * @brief Play a 2D sound effect + * + * Plays a sound effect without 3D positioning. The sound will be heard + * at the same volume regardless of listener position. + * + * @param name Name of the loaded sound effect to play + * @param volume Volume level (0.0 to 1.0+, default: 1.0) + * @param pitch Pitch multiplier (1.0 = normal pitch, default: 1.0) + * @param loop Whether to loop the sound continuously (default: false) + * @return Pointer to the AudioSource playing the sound, or nullptr if failed + */ AudioSource* PlaySound(const std::string& name, float volume = 1.0f, float pitch = 1.0f, bool loop = false); + + /** + * @brief Play a 3D positioned sound effect + * + * Plays a sound effect with 3D spatial positioning. The volume and stereo + * panning will be calculated based on the distance and direction from the listener. + * + * @param name Name of the loaded sound effect to play + * @param position 3D world position where the sound originates + * @param volume Base volume level before 3D attenuation (default: 1.0) + * @param pitch Pitch multiplier (1.0 = normal pitch, default: 1.0) + * @param loop Whether to loop the sound continuously (default: false) + * @return Pointer to the AudioSource playing the sound, or nullptr if failed + */ AudioSource* PlaySound3D(const std::string& name, const XMFLOAT3& position, float volume = 1.0f, float pitch = 1.0f, bool loop = false); + + /** + * @brief Stop a specific audio source + * + * Stops playback of the specified audio source and returns it to the + * available source pool for reuse. + * + * @param source Pointer to the AudioSource to stop + */ void StopSound(AudioSource* source); + + /** + * @brief Stop all currently playing sounds + * + * Immediately stops all active audio sources and returns them to the + * available pool. Useful for scene transitions or pause functionality. + */ void StopAllSounds(); + + /** + * @brief Pause all currently playing sounds + * + * Pauses all active audio sources without stopping them. Sounds can + * be resumed later with ResumeAllSounds(). + */ void PauseAllSounds(); + + /** + * @brief Resume all paused sounds + * + * Resumes playback of all previously paused audio sources. + */ void ResumeAllSounds(); + /** + * @brief Set the master volume level + * + * Adjusts the overall volume for all audio output. This affects all + * sound categories (SFX, music, etc.). + * + * @param volume Master volume level (0.0 = silent, 1.0 = full volume) + */ void SetMasterVolume(float volume); + + /** + * @brief Set the sound effects volume level + * + * Adjusts the volume level specifically for sound effects, allowing + * separate control from music and other audio categories. + * + * @param volume SFX volume level (0.0 = silent, 1.0 = full volume) + */ void SetSFXVolume(float volume); + + /** + * @brief Set the music volume level + * + * Adjusts the volume level specifically for music tracks, allowing + * separate control from sound effects and other audio categories. + * + * @param volume Music volume level (0.0 = silent, 1.0 = full volume) + */ void SetMusicVolume(float volume); + /** + * @brief Get the number of currently active audio sources + * + * Returns the count of audio sources that are currently playing sounds. + * Useful for debugging and performance monitoring. + * + * @return Number of active audio sources + */ size_t GetActiveSourceCount() const; private: + /** + * @brief Create an XAudio2 source voice for audio playback + * + * Internal method for creating source voices with the specified audio format. + * + * @param format Audio format description for the source voice + * @param voice Output parameter for the created source voice + * @return HRESULT indicating success or failure of voice creation + */ HRESULT CreateSourceVoice(const WAVEFORMATEX& format, IXAudio2SourceVoice** voice); + /** + * @brief Update all active audio sources + * + * Processes 3D audio calculations, updates source voice parameters, + * and handles audio source lifecycle management. + */ void UpdateSources(); + + /** + * @brief Get an available audio source from the pool + * + * Retrieves an unused audio source for playing a new sound. If no + * sources are available, may stop the oldest playing source. + * + * @return Pointer to an available AudioSource, or nullptr if none available + */ AudioSource* GetAvailableSource(); + + /** + * @brief Return an audio source to the available pool + * + * Marks an audio source as available for reuse and cleans up its state. + * + * @param source Pointer to the AudioSource to return to the pool + */ void ReturnSource(AudioSource* source); - IXAudio2* m_xAudio2; - IXAudio2MasteringVoice* m_masterVoice; - float m_masterVolume; - float m_sfxVolume; - float m_musicVolume; - size_t m_maxSources; + IXAudio2* m_xAudio2; ///< Main XAudio2 engine interface + IXAudio2MasteringVoice* m_masterVoice; ///< XAudio2 mastering voice for final output + float m_masterVolume; ///< Current master volume level + float m_sfxVolume; ///< Current sound effects volume level + float m_musicVolume; ///< Current music volume level + size_t m_maxSources; ///< Maximum number of simultaneous sources - std::vector> m_audioSources; - std::vector m_availableSources; - std::unordered_map> m_soundEffects; + std::vector> m_audioSources; ///< Pool of all audio sources + std::vector m_availableSources; ///< Pool of available sources + std::unordered_map> m_soundEffects; ///< Loaded sound effects by name }; \ No newline at end of file diff --git a/Spark Engine/Source/Audio/SoundEffect.h b/Spark Engine/Source/Audio/SoundEffect.h index 82f288b03..35554479a 100644 --- a/Spark Engine/Source/Audio/SoundEffect.h +++ b/Spark Engine/Source/Audio/SoundEffect.h @@ -1,4 +1,16 @@ -#pragma once +/** + * @file SoundEffect.h + * @brief Sound effect loading and procedural audio generation system + * @author Spark Engine Team + * @date 2025 + * + * This file provides comprehensive sound effect functionality including WAV file + * loading, in-memory audio buffer management, and a factory system for generating + * procedural sound effects. The system is designed to work efficiently with XAudio2 + * and provides both file-based and procedural audio capabilities. + */ + +#pragma once //------------------------------------------------------------------------------ // SoundEffect ‒ simple WAV loader + in-memory buffer @@ -11,77 +23,308 @@ #include #include -//────────────────────────────────────────────────────────────────────────────── -// SoundEffect -//────────────────────────────────────────────────────────────────────────────── +/** + * @brief Sound effect class for loading and managing audio data + * + * The SoundEffect class provides functionality for loading WAV audio files, + * storing audio data in memory, and providing access to audio format information. + * It supports both file-based loading and direct memory loading for procedural + * or streamed audio content. + * + * Features include: + * - WAV file format parsing and loading + * - In-memory audio buffer management + * - Audio format information access + * - Duration and sample rate queries + * - Memory-efficient storage with automatic cleanup + * + * @note Currently supports WAV format audio files + * @warning Ensure audio files are in supported formats before loading + */ class SoundEffect { public: + /** + * @brief Default constructor + * + * Initializes the sound effect with empty audio data and default format values. + */ SoundEffect(); + + /** + * @brief Destructor + * + * Automatically calls Unload() to ensure proper cleanup of audio resources. + */ ~SoundEffect(); - // ------------------------------------------------------------------ - // Loading / Unloading - // ------------------------------------------------------------------ + /** + * @brief Load audio data from a WAV file + * + * Loads and parses a WAV audio file, storing the audio data and format + * information for later playback through XAudio2. + * + * @param filename Path to the WAV file to load + * @return HRESULT indicating success or failure of loading operation + * @note Only WAV format files are currently supported + */ HRESULT LoadFromFile(const std::wstring& filename); + + /** + * @brief Load audio data from memory buffer + * + * Parses WAV format audio data from a memory buffer, useful for embedded + * audio resources or procedurally generated audio content. + * + * @param data Pointer to the audio data in WAV format + * @param dataSize Size of the audio data in bytes + * @return HRESULT indicating success or failure of parsing operation + */ HRESULT LoadFromMemory(const BYTE* data, DWORD dataSize); + + /** + * @brief Unload audio data and free memory + * + * Releases all audio data and resets the sound effect to an empty state. + * Safe to call multiple times. + */ void Unload(); - // ------------------------------------------------------------------ - // Accessors - // ------------------------------------------------------------------ + /** + * @brief Get the audio format structure + * @return Reference to the WAVEFORMATEX structure describing the audio format + */ const WAVEFORMATEX& GetFormat() const { return m_format; } + + /** + * @brief Get pointer to the raw audio data + * @return Pointer to the audio sample data, or nullptr if not loaded + */ const BYTE* GetData() const { return m_audioData.data(); } + + /** + * @brief Get the size of the audio data in bytes + * @return Size of the audio data buffer in bytes + */ DWORD GetDataSize() const { return m_audioDataSize; } + + /** + * @brief Check if audio data is currently loaded + * @return true if audio data is loaded, false if empty + */ bool IsLoaded() const { return m_audioDataSize != 0; } + /** + * @brief Get the duration of the audio in seconds + * @return Duration of the audio clip in seconds + */ float GetDuration() const; // seconds + + /** + * @brief Get the sample rate of the audio + * @return Sample rate in samples per second (Hz) + */ DWORD GetSampleRate() const { return m_format.nSamplesPerSec; } + + /** + * @brief Get the number of audio channels + * @return Number of channels (1 = mono, 2 = stereo, etc.) + */ WORD GetChannels() const { return m_format.nChannels; } + + /** + * @brief Get the bit depth of the audio samples + * @return Bits per sample (typically 8, 16, or 24) + */ WORD GetBitsPerSample()const { return m_format.wBitsPerSample; } private: - WAVEFORMATEX m_format; - std::vector m_audioData; - DWORD m_audioDataSize; + WAVEFORMATEX m_format; ///< Audio format description + std::vector m_audioData; ///< Raw audio sample data + DWORD m_audioDataSize; ///< Size of audio data in bytes - // internal helpers + /** + * @brief Parse WAV file format from memory buffer + * + * Internal method that parses WAV file headers and extracts audio data + * and format information from a memory buffer. + * + * @param data Pointer to WAV file data + * @param size Size of the WAV file data + * @return HRESULT indicating success or failure of parsing + */ HRESULT ParseWAVFile(const BYTE* data, DWORD size); + + /** + * @brief Find a specific chunk in WAV file data + * + * Searches for a chunk with the specified FourCC identifier in WAV file data. + * + * @param data Pointer to WAV file data + * @param dataSize Size of the WAV file data + * @param fourCC Four-character code identifying the chunk type + * @param outSize Output parameter for chunk size + * @param outPos Output parameter for chunk position + * @return HRESULT indicating success or failure of chunk location + */ HRESULT FindChunk(const BYTE* data, DWORD dataSize, DWORD fourCC, DWORD& outSize, DWORD& outPos); + + /** + * @brief Read data from a located chunk + * + * Reads the specified number of bytes from a chunk at the given position. + * + * @param data Pointer to source data + * @param pos Position within the data to start reading + * @param out Output buffer for read data + * @param bytes Number of bytes to read + * @return HRESULT indicating success or failure of read operation + */ HRESULT ReadChunkData(const BYTE* data, DWORD pos, void* out, DWORD bytes); // grant factory access to internals friend class SoundEffectFactory; }; -//────────────────────────────────────────────────────────────────────────────── -// SoundEffectFactory ‒ generate procedural SFX -//────────────────────────────────────────────────────────────────────────────── +/** + * @brief Factory class for generating procedural sound effects + * + * The SoundEffectFactory provides static methods for creating various types of + * procedural sound effects without requiring external audio files. This is useful + * for placeholder sounds, debugging, or games that prefer procedural audio. + * + * Features include: + * - Basic waveform generation (sine, beep, noise) + * - Game-specific sound effects (gunshots, explosions, footsteps) + * - Configurable parameters for frequency and duration + * - Automatic WAV format wrapping for XAudio2 compatibility + * + * @note All generated sounds are in standard PCM WAV format + * @warning Generated sounds are synthetic and may not be suitable for final game audio + */ class SoundEffectFactory { public: - // Simple procedural tones + /** + * @brief Create a simple beep tone + * + * Generates a basic square wave beep sound with the specified frequency and duration. + * + * @param freq Frequency of the beep in Hz (default: 440Hz - A4 note) + * @param dur Duration of the beep in seconds (default: 0.5 seconds) + * @return Unique pointer to the generated SoundEffect + */ static std::unique_ptr CreateBeep(float freq = 440.f, float dur = 0.5f); + + /** + * @brief Create a smooth sine wave tone + * + * Generates a pure sine wave tone with the specified frequency and duration. + * + * @param freq Frequency of the sine wave in Hz (default: 440Hz) + * @param dur Duration of the tone in seconds (default: 1.0 second) + * @return Unique pointer to the generated SoundEffect + */ static std::unique_ptr CreateSine(float freq = 440.f, float dur = 1.0f); + + /** + * @brief Create white noise + * + * Generates random white noise for the specified duration. + * + * @param dur Duration of the noise in seconds (default: 1.0 second) + * @return Unique pointer to the generated SoundEffect + */ static std::unique_ptr CreateNoise(float dur = 1.0f); - // Typical game sounds + /** + * @brief Create a gunshot sound effect + * + * Generates a procedural gunshot sound with appropriate frequency characteristics + * and envelope for realistic weapon audio. + * + * @return Unique pointer to the generated gunshot SoundEffect + */ static std::unique_ptr CreateGunshot(); + + /** + * @brief Create an explosion sound effect + * + * Generates a procedural explosion sound with low frequency rumble and + * high frequency crack components. + * + * @return Unique pointer to the generated explosion SoundEffect + */ static std::unique_ptr CreateExplosion(); + + /** + * @brief Create a footstep sound effect + * + * Generates a procedural footstep sound suitable for character movement audio. + * + * @return Unique pointer to the generated footstep SoundEffect + */ static std::unique_ptr CreateFootstep(); + + /** + * @brief Create a weapon reload sound effect + * + * Generates a procedural reload sound with metallic clicking characteristics. + * + * @return Unique pointer to the generated reload SoundEffect + */ static std::unique_ptr CreateReload(); + + /** + * @brief Create an item pickup sound effect + * + * Generates a pleasant pickup sound suitable for item collection feedback. + * + * @return Unique pointer to the generated pickup SoundEffect + */ static std::unique_ptr CreatePickup(); private: + /** + * @brief Generate waveform samples using a wave function + * + * Internal method for generating audio samples using mathematical wave functions. + * + * @param dst Output vector for generated samples + * @param freq Frequency of the waveform in Hz + * @param dur Duration of the waveform in seconds + * @param wave Function pointer to the wave generation function + */ static void GenerateWaveform(std::vector& dst, float freq, float dur, float (*wave)(float)); + + /** + * @brief Create a SoundEffect from sample data + * + * Internal method for wrapping raw sample data in a SoundEffect object + * with proper WAV format headers. + * + * @param samples Vector of 16-bit audio samples + * @param sampleRate Sample rate for the audio (default: 44100 Hz) + * @return Unique pointer to the created SoundEffect + */ static std::unique_ptr CreateFromSamples(const std::vector& samples, DWORD sampleRate = 44100); - // basic waves + /** + * @brief Generate sine wave sample + * @param phase Phase value for sine calculation (0 to 2π) + * @return Sine wave sample value + */ static float SineWave(float phase); + + /** + * @brief Generate noise sample + * @param phase Phase value (ignored for noise) + * @return Random noise sample value + */ static float NoiseWave(float); // phase ignored }; \ No newline at end of file diff --git a/Spark Engine/Source/Camera/SparkEngineCamera.h b/Spark Engine/Source/Camera/SparkEngineCamera.h index 8dfb9ad3f..5516152c7 100644 --- a/Spark Engine/Source/Camera/SparkEngineCamera.h +++ b/Spark Engine/Source/Camera/SparkEngineCamera.h @@ -1,4 +1,16 @@ -#pragma once +/** + * @file SparkEngineCamera.h + * @brief First-person camera system with smooth movement and controls + * @author Spark Engine Team + * @date 2025 + * + * This class provides a comprehensive first-person camera implementation with + * smooth movement, mouse look controls, zoom functionality, and proper matrix + * calculations for 3D rendering. The camera supports WASD movement, mouse look, + * vertical movement, and dynamic field of view adjustment. + */ + +#pragma once #ifndef _WIN32_WINNT #define _WIN32_WINNT 0x0A00 @@ -12,59 +24,193 @@ using DirectX::XMFLOAT3; using DirectX::XMMATRIX; +/** + * @brief First-person camera controller for 3D navigation + * + * The SparkEngineCamera class provides a complete first-person camera system + * with smooth movement, mouse look controls, and configurable parameters. + * It handles view and projection matrix calculations, movement input processing, + * and provides zoom functionality for gameplay mechanics. + * + * Features include: + * - Smooth first-person movement (forward, right, up) + * - Mouse look with pitch, yaw, and roll controls + * - Configurable movement and rotation speeds + * - Zoom functionality with different FOV settings + * - Automatic view matrix updates + * - Pitch clamping to prevent over-rotation + * + * @note Camera uses right-handed coordinate system with Y-up + * @warning Initialize() must be called before any movement or matrix operations + */ class SparkEngineCamera { private: - XMFLOAT3 m_position{ 0,0,0 }; - XMFLOAT3 m_forward{ 0,0,1 }; - XMFLOAT3 m_right{ 1,0,0 }; - XMFLOAT3 m_up{ 0,1,0 }; - float m_pitch{ 0 }, m_yaw{ 0 }, m_roll{ 0 }; + XMFLOAT3 m_position{ 0,0,0 }; ///< Camera position in world space + XMFLOAT3 m_forward{ 0,0,1 }; ///< Camera forward direction vector + XMFLOAT3 m_right{ 1,0,0 }; ///< Camera right direction vector + XMFLOAT3 m_up{ 0,1,0 }; ///< Camera up direction vector + float m_pitch{ 0 }, m_yaw{ 0 }, m_roll{ 0 }; ///< Camera rotation angles in radians - XMMATRIX m_viewMatrix{}; - XMMATRIX m_projectionMatrix{}; + XMMATRIX m_viewMatrix{}; ///< Cached view transformation matrix + XMMATRIX m_projectionMatrix{}; ///< Cached projection transformation matrix - float m_moveSpeed{ 10.0f }; - float m_rotationSpeed{ 2.0f }; - float m_defaultFov{ DirectX::XM_PIDIV2 }; - float m_zoomedFov{ DirectX::XM_PIDIV2 / 2.0f }; + float m_moveSpeed{ 10.0f }; ///< Movement speed in units per second + float m_rotationSpeed{ 2.0f }; ///< Rotation speed multiplier + float m_defaultFov{ DirectX::XM_PIDIV2 }; ///< Default field of view (90 degrees) + float m_zoomedFov{ DirectX::XM_PIDIV2 / 2.0f }; ///< Zoomed field of view (45 degrees) public: + /** + * @brief Default constructor + * + * Initializes camera with default values. Call Initialize() before use. + */ SparkEngineCamera() = default; + + /** + * @brief Default destructor + * + * Uses default cleanup as all resources are managed automatically. + */ ~SparkEngineCamera() = default; - // Must call before movement + /** + * @brief Initialize the camera with projection settings + * + * Sets up the camera with the specified aspect ratio and calculates + * the initial projection matrix. Must be called before movement operations. + * + * @param aspectRatio Screen width divided by height (e.g., 16/9 = 1.777) + * @note Call this after graphics system initialization and window creation + */ void Initialize(float aspectRatio); - // Update per-frame (recomputes view matrix) + /** + * @brief Update camera for the current frame + * + * Recalculates the view matrix based on current position and orientation. + * Should be called once per frame after processing movement input. + * + * @param deltaTime Time elapsed since last frame in seconds (currently unused) + */ void Update(float deltaTime); - // Movement + /** + * @brief Move camera forward or backward + * + * Moves the camera along its forward direction vector. Positive values + * move forward, negative values move backward. + * + * @param amount Distance to move (positive = forward, negative = backward) + */ void MoveForward(float amount); + + /** + * @brief Move camera left or right + * + * Moves the camera along its right direction vector. Positive values + * move right, negative values move left. + * + * @param amount Distance to move (positive = right, negative = left) + */ void MoveRight(float amount); + + /** + * @brief Move camera up or down + * + * Moves the camera along its up direction vector. Positive values + * move up, negative values move down. + * + * @param amount Distance to move (positive = up, negative = down) + */ void MoveUp(float amount); - // Rotation + /** + * @brief Rotate camera around X-axis (look up/down) + * + * Adjusts the camera's pitch rotation. Positive values pitch up, + * negative values pitch down. Pitch is automatically clamped to + * prevent over-rotation. + * + * @param angle Pitch angle to add in radians + */ void Pitch(float angle); + + /** + * @brief Rotate camera around Y-axis (look left/right) + * + * Adjusts the camera's yaw rotation. Positive values yaw right, + * negative values yaw left. + * + * @param angle Yaw angle to add in radians + */ void Yaw(float angle); + + /** + * @brief Rotate camera around Z-axis (tilt left/right) + * + * Adjusts the camera's roll rotation. Positive values roll clockwise, + * negative values roll counter-clockwise. + * + * @param angle Roll angle to add in radians + */ void Roll(float angle); - // Zoom toggle + /** + * @brief Toggle between normal and zoomed field of view + * + * Switches between default and zoomed FOV settings, useful for + * aiming mechanics or telescope effects. + * + * @param enabled true to enable zoom (narrow FOV), false for normal FOV + */ void SetZoom(bool enabled); - // Direct set + /** + * @brief Directly set the camera position + * + * Immediately positions the camera at the specified world coordinates + * and updates the view matrix. + * + * @param pos New position in world coordinates + */ void SetPosition(const XMFLOAT3& pos) { m_position = pos; UpdateViewMatrix(); } - // Accessors + /** + * @brief Get the current view transformation matrix + * @return 4x4 view matrix for rendering transformations + */ const XMMATRIX& GetViewMatrix() const { return m_viewMatrix; } + + /** + * @brief Get the current projection transformation matrix + * @return 4x4 projection matrix for rendering transformations + */ const XMMATRIX& GetProjectionMatrix() const { return m_projectionMatrix; } + + /** + * @brief Get the current camera position + * @return Position vector in world coordinates + */ const XMFLOAT3& GetPosition() const { return m_position; } + + /** + * @brief Get the current camera forward direction + * @return Normalized forward direction vector + */ const XMFLOAT3& GetForward() const { return m_forward; } private: + /** + * @brief Recalculate the view matrix from current transform + * + * Updates the cached view matrix based on current position and rotation. + * Called automatically when transform properties change. + */ void UpdateViewMatrix(); }; diff --git a/Spark Engine/Source/Core/SparkEngine.h b/Spark Engine/Source/Core/SparkEngine.h index 0db49da9b..3c539200f 100644 --- a/Spark Engine/Source/Core/SparkEngine.h +++ b/Spark Engine/Source/Core/SparkEngine.h @@ -1,4 +1,15 @@ -#pragma once +/** + * @file SparkEngine.h + * @brief Main engine header containing global declarations and forward declarations + * @author Spark Engine Team + * @date 2025 + * + * This file serves as the central header for the Spark Engine, providing forward + * declarations for core engine systems and global variable declarations that are + * shared across the entire engine framework. + */ + +#pragma once #include "resource.h" #include @@ -8,9 +19,42 @@ class Game; class InputManager; class Timer; -// Global variables +/** + * @brief Global application instance handle + * + * Windows application instance handle used throughout the engine + * for Win32 API calls and window management. + */ extern HINSTANCE hInst; + +/** + * @brief Global graphics engine instance + * + * Manages DirectX 11 rendering pipeline, device creation, swap chain, + * render targets, and all graphics-related operations. + */ extern std::unique_ptr g_graphics; + +/** + * @brief Global game instance + * + * Main game loop controller that manages scene updates, rendering, + * game objects, and coordinates between all engine systems. + */ extern std::unique_ptr g_game; + +/** + * @brief Global input manager instance + * + * Handles keyboard and mouse input processing, key mapping, + * and provides input state queries for the game systems. + */ extern std::unique_ptr g_input; + +/** + * @brief Global timer instance + * + * High-precision timing system for delta time calculation, + * frame rate management, and game loop timing control. + */ extern std::unique_ptr g_timer; \ No newline at end of file diff --git a/Spark Engine/Source/Core/framework.h b/Spark Engine/Source/Core/framework.h index 5f1742c65..53bcc03ef 100644 --- a/Spark Engine/Source/Core/framework.h +++ b/Spark Engine/Source/Core/framework.h @@ -1,4 +1,15 @@ -#pragma once +/** + * @file framework.h + * @brief Core framework header with essential includes and library links + * @author Spark Engine Team + * @date 2025 + * + * This header provides the fundamental includes required throughout the engine, + * including Windows API, DirectX 11, STL containers, and necessary library links. + * It serves as a precompiled header equivalent for the engine's core dependencies. + */ + +#pragma once #include "targetver.h" //#define WIN32_LEAN_AND_MEAN @@ -29,4 +40,3 @@ #pragma comment(lib, "dxgi.lib") using namespace DirectX; - diff --git a/Spark Engine/Source/Core/resource.h b/Spark Engine/Source/Core/resource.h index 77115d65f..a3ba3e48a 100644 --- a/Spark Engine/Source/Core/resource.h +++ b/Spark Engine/Source/Core/resource.h @@ -1,4 +1,15 @@ -//{{NO_DEPENDENCIES}} +/** + * @file resource.h + * @brief Windows resource definitions and identifiers + * @author Spark Engine Team + * @date 2025 + * + * This file contains Windows resource constants and identifiers used by the + * application's resource file (SparkEngine.rc). Generated by Microsoft Visual C++ + * and defines IDs for dialogs, icons, menus, and other UI resources. + */ + +//{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by SparkEngine.rc diff --git a/Spark Engine/Source/Core/targetver.h b/Spark Engine/Source/Core/targetver.h index 6a4df8b7d..265eff1fe 100644 --- a/Spark Engine/Source/Core/targetver.h +++ b/Spark Engine/Source/Core/targetver.h @@ -1,4 +1,16 @@ -#pragma once +/** + * @file targetver.h + * @brief Windows platform version targeting + * @author Spark Engine Team + * @date 2025 + * + * This header defines the Windows platform version that the application targets. + * Including SDKDDKVer.h defines the highest available Windows platform. To target + * a specific Windows version, include WinSDKVer.h and set _WIN32_WINNT before + * including SDKDDKVer.h. + */ + +#pragma once // Including SDKDDKVer.h defines the highest available Windows platform. // If you wish to build your application for a previous Windows platform, include WinSDKVer.h and diff --git a/Spark Engine/Source/Game/Console.h b/Spark Engine/Source/Game/Console.h index 33ee25687..853375e3e 100644 --- a/Spark Engine/Source/Game/Console.h +++ b/Spark Engine/Source/Game/Console.h @@ -1,4 +1,14 @@ -// Console.h +/** + * @file Console.h + * @brief Debug console system for runtime commands and logging + * @author Spark Engine Team + * @date 2025 + * + * This file provides a debug console interface that can be toggled during gameplay + * to execute commands, view log messages, and interact with the engine at runtime. + * The console supports command registration, input handling, and simple text rendering. + */ + #pragma once #include @@ -10,9 +20,21 @@ #include // std::wistringstream #include "Utils/Assert.h" -// ----------------------------------------------------------------------------- -// VERY-SIMPLE TEXT OUTPUT (no change) -// ----------------------------------------------------------------------------- +/** + * @brief Simple text output function for console rendering + * + * Basic text rendering utility that outputs text to the debug console. + * This is a placeholder implementation that uses OutputDebugString. + * + * @param text Text string to display + * @param x Horizontal position (currently unused) + * @param y Vertical position (currently unused) + * @param scale Text scale factor (currently unused) + * @param ctx DirectX device context (currently unused) + * + * @note This is a simple implementation using OutputDebugString + * @warning Parameters x, y, scale, and ctx are currently ignored + */ inline void DrawText(const std::wstring& text, float /*x*/, float /*y*/, float /*scale*/, ID3D11DeviceContext* /*ctx*/) @@ -21,35 +43,122 @@ inline void DrawText(const std::wstring& text, OutputDebugStringW(L"\n"); } -// ----------------------------------------------------------------------------- -// Console -// ----------------------------------------------------------------------------- +/** + * @brief Console command structure + * + * Represents a single console command with its name and callback function. + * Commands can be registered with the console and executed by typing the + * command name followed by optional arguments. + */ struct ConsoleCommand { - std::wstring name; - std::function&)> callback; + std::wstring name; ///< Command name as typed by the user + std::function&)> callback; ///< Function to execute when command is called }; +/** + * @brief Debug console for runtime interaction and logging + * + * The Console class provides a toggleable debug interface that allows developers + * to execute commands, view system logs, and interact with the engine during + * runtime. It handles keyboard input, maintains a command history, and provides + * basic text rendering for console output. + * + * Features include: + * - Toggle visibility with a hotkey (typically backtick `) + * - Command registration and execution + * - Scrolling text buffer for log messages + * - Input line editing with basic text input + * - Mouse cursor management + * + * @note Console uses wide character strings for Unicode support + * @warning Ensure Initialize() is called before using console functionality + */ class Console { public: + /** + * @brief Initialize the console system + * + * Sets up the console with the specified screen dimensions for proper + * positioning and sizing of the console interface. + * + * @param screenW Screen width in pixels + * @param screenH Screen height in pixels + */ void Initialize(int screenW, int screenH); + + /** + * @brief Toggle console visibility + * + * Shows or hides the console interface and manages the mouse cursor + * visibility accordingly. + */ void Toggle() { visible = !visible; ShowCursor(visible); } + + /** + * @brief Check if the console is currently visible + * @return true if console is visible and active, false otherwise + */ bool IsVisible() const { return visible; } + /** + * @brief Handle character input for console text entry + * + * Processes WM_CHAR messages to build the current input line. + * Handles printable characters and adds them to the input buffer. + * + * @param c Wide character from WM_CHAR message + * @return true if character was handled, false otherwise + */ bool HandleChar(wchar_t c); // WM_CHAR + + /** + * @brief Handle key down events for console control + * + * Processes WM_KEYDOWN messages for special keys like Enter, Backspace, + * and other control keys that affect console operation. + * + * @param key Virtual key code from WM_KEYDOWN message + * @return true if key was handled, false otherwise + */ bool HandleKeyDown(WPARAM key); // WM_KEYDOWN + /** + * @brief Add a log message to the console buffer + * + * Appends a new message to the console's scrolling text buffer. + * The message will be visible when the console is open. + * + * @param msg Log message to add to the console + */ void Log(const std::wstring& msg); + + /** + * @brief Render the console interface + * + * Draws the console background, text buffer, and input line to the screen. + * Only renders if the console is currently visible. + * + * @param ctx DirectX device context for rendering operations + */ void Render(ID3D11DeviceContext* ctx); private: - bool visible{ false }; - int width{ 0 }, height{ 0 }; + bool visible{ false }; ///< Whether console is currently visible + int width{ 0 }, height{ 0 }; ///< Screen dimensions for positioning - std::vector buffer; // rolling log - std::wstring inputLine; // current user input - std::vector commands; // registered commands + std::vector buffer; ///< Rolling log buffer for console messages + std::wstring inputLine; ///< Current user input line + std::vector commands; ///< Registered console commands + /** + * @brief Parse and execute a command line + * + * Takes a complete command line, parses it into command name and arguments, + * and executes the corresponding registered command if found. + * + * @param line Complete command line string to execute + */ void ExecuteCommand(const std::wstring& line); }; \ No newline at end of file diff --git a/Spark Engine/Source/Game/Game.h b/Spark Engine/Source/Game/Game.h index 61bc9495e..bbaa6da5c 100644 --- a/Spark Engine/Source/Game/Game.h +++ b/Spark Engine/Source/Game/Game.h @@ -1,4 +1,16 @@ -#pragma once +/** + * @file Game.h + * @brief Main game class managing the core game loop and scene systems + * @author Spark Engine Team + * @date 2025 + * + * The Game class serves as the central coordinator for all game systems, + * managing the main game loop, scene updates, rendering operations, and + * coordination between different engine subsystems like graphics, input, + * camera, and game objects. + */ + +#pragma once #include "..\Core\framework.h" // XMFLOAT3, XMMATRIX, HRESULT #include "Utils/Assert.h" @@ -21,44 +33,137 @@ struct ConstantBuffer; #include "PlaneObject.h" #include "SphereObject.h" +/** + * @brief Main game controller class managing the game loop and scene + * + * The Game class is responsible for coordinating all game systems and managing + * the main game loop. It handles initialization of game objects, processing + * user input, updating game state, and rendering the scene. This class serves + * as the bridge between the engine systems and the actual game content. + * + * @note The Game class does not own the graphics or input systems, but holds references + * @warning Ensure Initialize() is called before any Update() or Render() operations + */ class Game { public: + /** + * @brief Default constructor + * + * Initializes member variables to safe default values. The actual game + * systems are set up in the Initialize() method. + */ Game(); + + /** + * @brief Destructor + * + * Automatically calls Shutdown() to ensure proper cleanup of all game systems. + */ ~Game(); - // Engine & scene initialization / teardown + /** + * @brief Initialize the game systems and scene + * + * Sets up all game systems including camera, shaders, player, projectile pool, + * and creates initial test objects in the scene. Must be called after the + * graphics and input systems are initialized. + * + * @param graphics Pointer to the initialized graphics engine + * @param input Pointer to the initialized input manager + * @return HRESULT indicating success or failure of game initialization + * @note The graphics and input pointers are stored but not owned by Game + */ HRESULT Initialize(GraphicsEngine* graphics, InputManager* input); + + /** + * @brief Clean up all game systems and objects + * + * Shuts down all game subsystems and clears the scene. Safe to call + * multiple times. + */ void Shutdown(); - // Main loop hooks + /** + * @brief Update the game state for the current frame + * + * Processes input, updates camera, updates all game objects, and handles + * game logic. Called once per frame during the main game loop. + * + * @param deltaTime Time elapsed since the last frame in seconds + * @note If the game is paused, this method returns immediately + */ void Update(float deltaTime); + + /** + * @brief Render the current frame + * + * Issues rendering commands for all visible game objects and manages + * the rendering pipeline for the current frame. Should be called after + * Update() during the main game loop. + */ void Render(); - // Pause helpers + /** + * @brief Pause the game simulation + * + * Stops game updates while maintaining rendering. Useful for pause menus + * or when the game window loses focus. + */ void Pause() { m_isPaused = true; } + + /** + * @brief Resume the game simulation + * + * Resumes game updates from a paused state. + */ void Resume() { m_isPaused = false; } + + /** + * @brief Check if the game is currently paused + * @return true if game is paused, false if running + */ bool IsPaused() const { return m_isPaused; } private: - // Internal helpers + /** + * @brief Update the camera based on input and game state + * @param dt Delta time for frame-rate independent movement + */ void UpdateCamera(float dt); + + /** + * @brief Update all game objects in the scene + * @param dt Delta time for frame-rate independent updates + */ void UpdateGameObjects(float dt); + + /** + * @brief Process input and translate to game actions + * @param dt Delta time for frame-rate independent input handling + */ void HandleInput(float dt); + + /** + * @brief Create initial test objects for the scene + * + * Populates the scene with basic objects for testing and demonstration + * purposes. Called during initialization. + */ void CreateTestObjects(); // Engine-side pointers (not owned) - GraphicsEngine* m_graphics{ nullptr }; - InputManager* m_input{ nullptr }; + GraphicsEngine* m_graphics{ nullptr }; ///< Reference to graphics engine + InputManager* m_input{ nullptr }; ///< Reference to input manager // Sub-systems owned by Game - std::unique_ptr m_camera; - std::unique_ptr m_shader; - std::unique_ptr m_player; - std::unique_ptr m_projectilePool; + std::unique_ptr m_camera; ///< First-person camera system + std::unique_ptr m_shader; ///< Shader management + std::unique_ptr m_player; ///< Player controller + std::unique_ptr m_projectilePool; ///< Projectile object pool // Scene objects - std::vector> m_gameObjects; + std::vector> m_gameObjects; ///< All game objects in the scene - bool m_isPaused{ false }; + bool m_isPaused{ false }; ///< Current pause state of the game }; \ No newline at end of file diff --git a/Spark Engine/Source/Game/GameObject.h b/Spark Engine/Source/Game/GameObject.h index 83cc6a196..9e4bac00e 100644 --- a/Spark Engine/Source/Game/GameObject.h +++ b/Spark Engine/Source/Game/GameObject.h @@ -1,4 +1,16 @@ -#pragma once +/** + * @file GameObject.h + * @brief Base class for all interactive objects in the game world + * @author Spark Engine Team + * @date 2025 + * + * This class provides the fundamental interface and functionality for all objects + * that can exist in the game world. It handles transformation, rendering, collision + * callbacks, and basic object management. All concrete game objects should inherit + * from this base class. + */ + +#pragma once #include "..\Core\framework.h" // XMFLOAT3, XMMATRIX, HRESULT #include "..\Graphics\Mesh.h" @@ -10,81 +22,294 @@ namespace Projectiles { class Projectile; } using Projectiles::Projectile; +/** + * @brief Base class for all game objects in the world + * + * GameObject provides the fundamental interface and functionality required by all + * interactive objects in the game world. This includes 3D transformation, mesh + * rendering, collision detection callbacks, and basic object lifecycle management. + * + * All concrete game objects (players, enemies, items, etc.) should inherit from + * this class and implement the pure virtual collision callback methods. + * + * @note This is an abstract class that cannot be instantiated directly + * @warning Derived classes must implement OnHit() and OnHitWorld() methods + */ class GameObject { public: + /** + * @brief Default constructor + * + * Initializes the game object with default transform values and assigns + * a unique ID for object identification. + */ GameObject(); + + /** + * @brief Virtual destructor + * + * Ensures proper cleanup when derived objects are destroyed polymorphically. + * Automatically calls Shutdown() to clean up resources. + */ virtual ~GameObject(); - // Core lifecycle + /** + * @brief Initialize the game object with DirectX resources + * + * Sets up the object for rendering by storing DirectX device references + * and calling the virtual CreateMesh() method for mesh setup. + * + * @param device DirectX 11 device for resource creation + * @param context DirectX 11 device context for rendering operations + * @return HRESULT indicating success or failure of initialization + */ virtual HRESULT Initialize(ID3D11Device* device, ID3D11DeviceContext* context); + + /** + * @brief Update the game object for the current frame + * + * Called once per frame to update object-specific logic, animations, + * physics, or other time-dependent behavior. + * + * @param deltaTime Time elapsed since the last frame in seconds + */ virtual void Update(float deltaTime); + + /** + * @brief Render the game object to the screen + * + * Renders the object's mesh using the current world transform and the + * provided view and projection matrices. + * + * @param view Camera view transformation matrix + * @param projection Camera projection transformation matrix + */ virtual void Render(const XMMATRIX& view, const XMMATRIX& projection); + + /** + * @brief Clean up all resources used by the game object + * + * Releases mesh resources and resets the object state. Safe to call + * multiple times. + */ virtual void Shutdown(); - // Hit callbacks (must be overridden by subclasses) + /** + * @brief Collision callback when this object hits another game object + * + * Pure virtual method that must be implemented by derived classes to handle + * collision events with other game objects. + * + * @param target Pointer to the game object that was hit + */ virtual void OnHit(GameObject* target) = 0; + + /** + * @brief Collision callback when this object hits the world geometry + * + * Pure virtual method that must be implemented by derived classes to handle + * collision events with static world geometry. + * + * @param hitPoint World position where the collision occurred + * @param normal Surface normal at the collision point + */ virtual void OnHitWorld(const XMFLOAT3& hitPoint, const XMFLOAT3& normal) = 0; - // Transform + /** + * @brief Set the world position of the object + * @param pos New position in world coordinates + */ void SetPosition(const XMFLOAT3& pos); + + /** + * @brief Set the rotation of the object + * @param rot New rotation in Euler angles (radians) + */ void SetRotation(const XMFLOAT3& rot); + + /** + * @brief Set the scale of the object + * @param scale New scale factors for X, Y, and Z axes + */ void SetScale(const XMFLOAT3& scale); + + /** + * @brief Move the object by a relative offset + * @param delta Position offset to apply + */ void Translate(const XMFLOAT3& delta); + + /** + * @brief Rotate the object by additional rotation + * @param delta Rotation offset to apply (radians) + */ void Rotate(const XMFLOAT3& delta); + + /** + * @brief Scale the object by additional factors + * @param delta Scale factors to multiply with current scale + */ void Scale(const XMFLOAT3& delta); - // Accessors + /** + * @brief Get the current world position + * @return Current position in world coordinates + */ const XMFLOAT3& GetPosition() const { return m_position; } + + /** + * @brief Get the current rotation + * @return Current rotation in Euler angles (radians) + */ const XMFLOAT3& GetRotation() const { return m_rotation; } + + /** + * @brief Get the current scale + * @return Current scale factors for X, Y, and Z axes + */ const XMFLOAT3& GetScale() const { return m_scale; } + /** + * @brief Get the world transformation matrix + * + * Computes and returns the world matrix combining position, rotation, and scale. + * The matrix is cached and only recomputed when the transform changes. + * + * @return 4x4 world transformation matrix + */ XMMATRIX GetWorldMatrix(); + + /** + * @brief Get the object's forward direction vector + * @return Normalized forward vector in world space + */ XMFLOAT3 GetForward() const; + + /** + * @brief Get the object's right direction vector + * @return Normalized right vector in world space + */ XMFLOAT3 GetRight() const; + + /** + * @brief Get the object's up direction vector + * @return Normalized up vector in world space + */ XMFLOAT3 GetUp() const; + /** + * @brief Check if the object is active + * @return true if object is active and should be updated + */ bool IsActive() const { return m_active; } + + /** + * @brief Check if the object is visible + * @return true if object is visible and should be rendered + */ bool IsVisible() const { return m_visible; } + + /** + * @brief Set the active state of the object + * @param v true to activate, false to deactivate + */ void SetActive(bool v) { m_active = v; } + + /** + * @brief Set the visibility state of the object + * @param v true to make visible, false to hide + */ void SetVisible(bool v) { m_visible = v; } + /** + * @brief Get the unique identifier of the object + * @return Unique ID assigned during construction + */ UINT GetID() const { return m_id; } + + /** + * @brief Get the name of the object + * @return Current object name string + */ const std::string& GetName() const { return m_name; } + + /** + * @brief Set the name of the object + * @param n New name for the object + */ void SetName(const std::string& n) { m_name = n; } + /** + * @brief Get the mesh associated with this object + * @return Pointer to the object's mesh, or nullptr if no mesh is set + */ Mesh* GetMesh() const { return m_mesh.get(); } + /** + * @brief Calculate distance to another game object + * @param o Other game object to measure distance to + * @return Distance in world units + */ float GetDistanceFrom(const GameObject& o) const; + + /** + * @brief Calculate distance to a world position + * @param p World position to measure distance to + * @return Distance in world units + */ float GetDistanceFrom(const XMFLOAT3& p) const; protected: - // Internal helpers + /** + * @brief Create or set up the mesh for this object + * + * Virtual method that derived classes should override to create their + * specific mesh geometry. Called during initialization. + */ virtual void CreateMesh(); + + /** + * @brief Update the cached world transformation matrix + * + * Recalculates the world matrix from current position, rotation, and scale + * values. Called automatically when transform properties change. + */ void UpdateWorldMatrix(); // Transform state - XMFLOAT3 m_position{}; - XMFLOAT3 m_rotation{}; - XMFLOAT3 m_scale{ 1,1,1 }; - XMMATRIX m_worldMatrix{}; - bool m_worldMatrixDirty{ true }; + XMFLOAT3 m_position{}; ///< World position + XMFLOAT3 m_rotation{}; ///< Rotation in Euler angles (radians) + XMFLOAT3 m_scale{ 1,1,1 }; ///< Scale factors for each axis + XMMATRIX m_worldMatrix{}; ///< Cached world transformation matrix + bool m_worldMatrixDirty{ true }; ///< Flag indicating if world matrix needs recalculation // Rendering - std::unique_ptr m_mesh; - ID3D11Device* m_device{ nullptr }; - ID3D11DeviceContext* m_context{ nullptr }; + std::unique_ptr m_mesh; ///< 3D mesh for rendering + ID3D11Device* m_device{ nullptr }; ///< DirectX device reference + ID3D11DeviceContext* m_context{ nullptr }; ///< DirectX context reference // Visibility/activation - bool m_active{ true }; - bool m_visible{ true }; + bool m_active{ true }; ///< Whether object should be updated + bool m_visible{ true }; ///< Whether object should be rendered // Identification - static UINT s_nextID; - UINT m_id{ 0 }; - std::string m_name; + static UINT s_nextID; ///< Static counter for unique ID generation + UINT m_id{ 0 }; ///< Unique identifier for this object + std::string m_name; ///< Human-readable name for debugging private: + /** + * @brief Copy constructor (deleted) + * + * GameObjects cannot be copied to prevent resource management issues. + */ GameObject(const GameObject&) = delete; + + /** + * @brief Assignment operator (deleted) + * + * GameObjects cannot be assigned to prevent resource management issues. + */ GameObject& operator=(const GameObject&) = delete; }; \ No newline at end of file diff --git a/Spark Engine/Source/Game/Player.h b/Spark Engine/Source/Game/Player.h index 4daa049c0..b02428142 100644 --- a/Spark Engine/Source/Game/Player.h +++ b/Spark Engine/Source/Game/Player.h @@ -1,4 +1,15 @@ -#pragma once +/** + * @file Player.h + * @brief Player character controller with movement, combat, and health systems + * @author Spark Engine Team + * @date 2025 + * + * The Player class represents the player character in the game world, inheriting + * from GameObject and providing comprehensive first-person character functionality + * including movement, jumping, weapon handling, health/armor systems, and combat. + */ + +#pragma once #include "GameObject.h" #include "Utils/Assert.h" @@ -9,91 +20,300 @@ #include "..\Utils\MathUtils.h" #include +/** + * @brief Player character controller class + * + * The Player class provides a complete first-person character controller with + * movement physics, weapon systems, health management, and combat mechanics. + * It integrates with the camera system for first-person perspective and the + * input system for responsive controls. + * + * Features include: + * - First-person movement (WASD, jump, crouch, run) + * - Health and armor systems with damage/healing + * - Weapon system with multiple weapon types and reloading + * - Physics-based movement with gravity and collision + * - Animation systems (head bobbing, footsteps) + * + * @note The Player does not own the camera, input manager, or projectile pool references + * @warning Ensure SetProjectilePool() is called before using weapons + */ class Player : public GameObject { public: + /** + * @brief Default constructor + * + * Initializes player stats, movement parameters, and combat variables + * to default values suitable for first-person gameplay. + */ Player(); + + /** + * @brief Default destructor + * + * Uses default cleanup as all resources are managed automatically. + */ ~Player() override = default; - // Note: signature matches GameObject::Initialize + /** + * @brief Initialize the player with required engine systems + * + * Sets up the player character with DirectX resources and engine system + * references. Configures the player for gameplay with camera and input. + * + * @param device DirectX 11 device for resource creation + * @param context DirectX 11 device context for rendering + * @param camera Pointer to the first-person camera system + * @param input Pointer to the input manager for controls + * @return HRESULT indicating success or failure of initialization + * @note The camera and input pointers are stored but not owned by Player + */ HRESULT Initialize(ID3D11Device* device, ID3D11DeviceContext* context, SparkEngineCamera* camera, InputManager* input); + /** + * @brief Update player logic for the current frame + * + * Processes input, updates movement physics, handles combat timing, + * updates animations, and manages player state for the current frame. + * + * @param dt Delta time since last frame in seconds + */ void Update(float dt) override; + + /** + * @brief Render the player (typically no visual representation in first-person) + * + * In first-person mode, this typically doesn't render anything visible. + * May be used for debugging visualization or third-person mode. + * + * @param view Camera view transformation matrix + * @param proj Camera projection transformation matrix + */ void Render(const DirectX::XMMATRIX& view, const DirectX::XMMATRIX& proj) override; - // Damage & healing + /** + * @brief Apply damage to the player + * + * Reduces player health, accounting for armor protection. Can result + * in player death if health reaches zero. + * + * @param dmg Amount of damage to apply (positive value) + */ void TakeDamage(float dmg); + + /** + * @brief Restore player health + * + * Increases player health up to the maximum health limit. + * + * @param amt Amount of health to restore (positive value) + */ void Heal(float amt); + + /** + * @brief Increase player armor + * + * Adds armor points up to the maximum armor limit. + * + * @param amt Amount of armor to add (positive value) + */ void AddArmor(float amt); - // Movement & combat + /** + * @brief Execute a jump if the player is grounded + * + * Applies upward velocity for jumping. Only works if the player + * is currently on the ground. + */ void Jump(); + + /** + * @brief Begin reloading the current weapon + * + * Starts the reload process for the current weapon if not already + * reloading and if the weapon can be reloaded. + */ void StartReload(); + + /** + * @brief Fire the current weapon + * + * Attempts to fire the current weapon if ammunition is available, + * the weapon is not on cooldown, and not currently reloading. + */ void Fire(); + + /** + * @brief Switch to a different weapon type + * + * Changes the current weapon to the specified type and resets + * weapon-specific timers and ammunition. + * + * @param t New weapon type to switch to + */ void ChangeWeapon(WeaponType t); - // Assign external pool + /** + * @brief Set the projectile pool for weapon projectiles + * + * Assigns the projectile pool that will be used when firing weapons. + * This must be set before the player can use weapons. + * + * @param pool Pointer to the projectile object pool + * @warning Must not be null - assertion will fail if null is passed + */ void SetProjectilePool(ProjectilePool* pool) { ASSERT_NOT_NULL(pool); m_projectilePool = pool; } - // Status + /** + * @brief Get current player health + * @return Current health value + */ float GetHealth() const { return m_health; } + + /** + * @brief Get maximum player health + * @return Maximum health value + */ float GetMaxHealth() const { return m_maxHealth; } + + /** + * @brief Check if the player is alive + * @return true if health is above zero, false if dead + */ bool IsAlive() const { return m_health > 0.0f; } + /** + * @brief Set the running state of the player + * @param v true to enable running, false for normal walking speed + */ void SetRunning(bool v) { m_isRunning = v; } + + /** + * @brief Set the crouching state of the player + * @param v true to crouch, false to stand normally + */ void SetCrouching(bool v) { m_isCrouching = v; } - // Hit callbacks + /** + * @brief Collision callback when player hits another game object + * + * Handles interactions when the player collides with other objects + * in the game world (items, enemies, etc.). + * + * @param target Pointer to the game object that was hit + */ void OnHit(GameObject* target) override; + + /** + * @brief Collision callback when player hits world geometry + * + * Handles collisions with static world geometry like walls, floors, + * and other environmental objects. + * + * @param hitPoint World position where the collision occurred + * @param normal Surface normal at the collision point + */ void OnHitWorld(const DirectX::XMFLOAT3& hitPoint, const DirectX::XMFLOAT3& normal) override; private: // Stats - float m_health{ 100 }, m_maxHealth{ 100 }; - float m_armor{ 0 }, m_maxArmor{ 100 }; - float m_stamina{ 100 }, m_maxStamina{ 100 }; - float m_speed{ 5 }, m_jumpHeight{ 3 }; + float m_health{ 100 }, m_maxHealth{ 100 }; ///< Current and maximum health + float m_armor{ 0 }, m_maxArmor{ 100 }; ///< Current and maximum armor + float m_stamina{ 100 }, m_maxStamina{ 100 }; ///< Current and maximum stamina + float m_speed{ 5 }, m_jumpHeight{ 3 }; ///< Movement speed and jump height // Movement - DirectX::XMFLOAT3 m_velocity{}; - bool m_isGrounded{ true }, m_isRunning{ false }, + DirectX::XMFLOAT3 m_velocity{}; ///< Current velocity vector + bool m_isGrounded{ true }, m_isRunning{ false }, ///< Movement state flags m_isCrouching{ false }, m_isJumping{ false }; // Combat - WeaponStats m_currentWeapon; - int m_currentAmmo{ 0 }; - float m_fireTimer{ 0 }, m_reloadTimer{ 0 }; - bool m_isReloading{ false }, m_isFiring{ false }; + WeaponStats m_currentWeapon; ///< Current weapon configuration + int m_currentAmmo{ 0 }; ///< Current ammunition count + float m_fireTimer{ 0 }, m_reloadTimer{ 0 }; ///< Weapon timing + bool m_isReloading{ false }, m_isFiring{ false }; ///< Combat state - // External - SparkEngineCamera* m_camera{ nullptr }; - InputManager* m_input{ nullptr }; - ProjectilePool* m_projectilePool{ nullptr }; + // External references (not owned) + SparkEngineCamera* m_camera{ nullptr }; ///< Reference to camera system + InputManager* m_input{ nullptr }; ///< Reference to input manager + ProjectilePool* m_projectilePool{ nullptr }; ///< Reference to projectile pool // Collision & animation - BoundingSphere m_collisionSphere; - float m_bobTimer{ 0 }, m_footstepTimer{ 0 }; + BoundingSphere m_collisionSphere; ///< Collision bounds for player + float m_bobTimer{ 0 }, m_footstepTimer{ 0 }; ///< Animation timers - // Helpers + /** + * @brief Process input for movement and actions + * @param dt Delta time for frame-rate independent input + */ void HandleInput(float dt); + + /** + * @brief Update movement based on input and physics + * @param dt Delta time for frame-rate independent movement + */ void UpdateMovement(float dt); + + /** + * @brief Update weapon timers and combat state + * @param dt Delta time for frame-rate independent timing + */ void UpdateCombat(float dt); + + /** + * @brief Update physics simulation (gravity, velocity, etc.) + * @param dt Delta time for frame-rate independent physics + */ void UpdatePhysics(float dt); + + /** + * @brief Update animation timers and effects + * @param dt Delta time for frame-rate independent animation + */ void UpdateAnimation(float dt); + + /** + * @brief Check and resolve collisions with world geometry + */ void UpdateCollision(); + + /** + * @brief Apply gravity to player velocity + * @param dt Delta time for frame-rate independent gravity + */ void ApplyGravity(float dt); + + /** + * @brief Check if player is touching the ground + */ void CheckGroundCollision(); + + /** + * @brief Handle footstep sound timing + * @param dt Delta time for frame-rate independent audio + */ void HandleFootsteps(float dt); + /** + * @brief Get weapon statistics for a specific weapon type + * @param type Weapon type to get stats for + * @return WeaponStats structure with weapon parameters + */ WeaponStats GetWeaponStats(WeaponType type); + + /** + * @brief Calculate the direction vector for projectile firing + * @return Normalized direction vector from camera forward + */ DirectX::XMFLOAT3 CalculateFireDirection(); }; \ No newline at end of file diff --git a/Spark Engine/Source/Graphics/GraphicsEngine.h b/Spark Engine/Source/Graphics/GraphicsEngine.h index e56c1607e..5cd82899e 100644 --- a/Spark Engine/Source/Graphics/GraphicsEngine.h +++ b/Spark Engine/Source/Graphics/GraphicsEngine.h @@ -1,4 +1,14 @@ -// GraphicsEngine.h +/** + * @file GraphicsEngine.h + * @brief DirectX 11 graphics engine core implementation + * @author Spark Engine Team + * @date 2025 + * + * This class manages the entire DirectX 11 rendering pipeline including device creation, + * swap chain management, render target setup, depth buffer configuration, and frame + * rendering operations. It serves as the central graphics system for the Spark Engine. + */ + #pragma once #include "Utils/Assert.h" @@ -11,43 +21,139 @@ using Microsoft::WRL::ComPtr; +/** + * @brief Core DirectX 11 graphics engine class + * + * The GraphicsEngine class encapsulates all DirectX 11 functionality required for + * rendering 3D graphics in the Spark Engine. It manages device initialization, + * resource creation, and provides a clean interface for rendering operations. + * + * @note This class follows RAII principles and automatically handles resource cleanup + * @warning Ensure Initialize() is called before any rendering operations + */ class GraphicsEngine { public: + /** + * @brief Default constructor + * + * Initializes member variables to safe default values. The actual DirectX + * device and resources are created in the Initialize() method. + */ GraphicsEngine(); + + /** + * @brief Destructor + * + * Automatically calls Shutdown() to ensure proper resource cleanup. + */ ~GraphicsEngine(); - // Initialize device, swap chain, RTV/DSV, debug filters + /** + * @brief Initialize the graphics engine with DirectX 11 + * + * Creates the DirectX 11 device, device context, swap chain, render target view, + * and depth stencil view. Also sets up debug output filters and viewport. + * + * @param hWnd Handle to the window for rendering + * @return HRESULT indicating success or failure of initialization + * @note Must be called before any rendering operations + * @warning Calling this multiple times without Shutdown() will cause resource leaks + */ HRESULT Initialize(HWND hWnd); - // Cleanup + /** + * @brief Clean up all DirectX resources + * + * Releases all COM interfaces and resets internal state. Safe to call + * multiple times. + */ void Shutdown(); - // Frame operations + /** + * @brief Begin a new rendering frame + * + * Clears the render target and depth buffer, preparing for new frame rendering. + * Should be called at the start of each frame before any draw operations. + */ void BeginFrame(); + + /** + * @brief Complete the current frame and present to screen + * + * Presents the completed frame to the display. Should be called after all + * draw operations for the current frame are complete. + */ void EndFrame(); - // Handle window resize + /** + * @brief Handle window resize events + * + * Recreates the swap chain buffers and adjusts the viewport to match + * the new window dimensions. + * + * @param width New window width in pixels + * @param height New window height in pixels + */ void OnResize(UINT width, UINT height); - // Accessors + /** + * @brief Get the DirectX 11 device + * @return Pointer to the ID3D11Device interface + * @note Returns nullptr if Initialize() hasn't been called successfully + */ ID3D11Device* GetDevice() const { return m_device.Get(); } + + /** + * @brief Get the DirectX 11 device context + * @return Pointer to the ID3D11DeviceContext interface + * @note Returns nullptr if Initialize() hasn't been called successfully + */ ID3D11DeviceContext* GetContext() const { return m_context.Get(); } + + /** + * @brief Get the current window width + * @return Window width in pixels + */ UINT GetWindowWidth() const { return m_windowWidth; } + + /** + * @brief Get the current window height + * @return Window height in pixels + */ UINT GetWindowHeight() const { return m_windowHeight; } private: + /** + * @brief Create DirectX device and swap chain + * @param hWnd Window handle for the swap chain + * @return HRESULT indicating success or failure + */ HRESULT CreateDeviceAndSwapChain(HWND hWnd); + + /** + * @brief Create the render target view from swap chain back buffer + * @return HRESULT indicating success or failure + */ HRESULT CreateRenderTargetView(); + + /** + * @brief Create depth stencil buffer and view + * @return HRESULT indicating success or failure + */ HRESULT CreateDepthStencilView(); + + /** + * @brief Configure the rendering viewport + */ void SetViewport(); - ComPtr m_device; - ComPtr m_context; - ComPtr m_swapChain; - ComPtr m_renderTargetView; - ComPtr m_depthStencilView; + ComPtr m_device; ///< DirectX 11.1 device + ComPtr m_context; ///< DirectX 11.1 device context + ComPtr m_swapChain; ///< DXGI swap chain for presentation + ComPtr m_renderTargetView; ///< Render target view for back buffer + ComPtr m_depthStencilView; ///< Depth stencil view for depth testing - UINT m_windowWidth; - UINT m_windowHeight; + UINT m_windowWidth; ///< Current window width in pixels + UINT m_windowHeight; ///< Current window height in pixels }; \ No newline at end of file diff --git a/Spark Engine/Source/Graphics/Mesh.h b/Spark Engine/Source/Graphics/Mesh.h index 0eb0f2bca..8bfb0e51b 100644 --- a/Spark Engine/Source/Graphics/Mesh.h +++ b/Spark Engine/Source/Graphics/Mesh.h @@ -1,4 +1,14 @@ -// Mesh.h +/** + * @file Mesh.h + * @brief 3D mesh management and primitive generation system + * @author Spark Engine Team + * @date 2025 + * + * This class provides comprehensive 3D mesh functionality including vertex/index + * buffer management, primitive shape generation (cube, sphere, plane), and mesh + * loading capabilities for the Spark Engine's rendering system. + */ + #pragma once #include "Utils/Assert.h" @@ -12,14 +22,32 @@ using DirectX::XMFLOAT2; using DirectX::XMFLOAT3; using DirectX::XMMATRIX; +/** + * @brief 3D vertex structure with position, normal, and texture coordinates + * + * Standard vertex format used throughout the Spark Engine for 3D geometry. + * Includes validation to ensure all floating-point values are finite. + */ struct Vertex { - XMFLOAT3 Position; - XMFLOAT3 Normal; - XMFLOAT2 TexCoord; + XMFLOAT3 Position; ///< 3D world position + XMFLOAT3 Normal; ///< Surface normal vector for lighting calculations + XMFLOAT2 TexCoord; ///< Texture coordinates for UV mapping + /** + * @brief Default constructor with safe default values + */ Vertex() : Position{ 0,0,0 }, Normal{ 0,1,0 }, TexCoord{ 0,0 } {} + /** + * @brief Parameterized constructor with validation + * + * @param p 3D position vector + * @param n Normal vector (should be normalized) + * @param t Texture coordinate vector + * + * @note Includes assertions to validate that all values are finite + */ Vertex(const XMFLOAT3& p, const XMFLOAT3& n, const XMFLOAT2& t) @@ -31,50 +59,189 @@ struct Vertex } }; +/** + * @brief Container for mesh vertex and index data + * + * Simple data structure that holds the raw vertex and index arrays + * for mesh construction and manipulation. + */ struct MeshData { - std::vector vertices; - std::vector indices; + std::vector vertices; ///< Array of mesh vertices + std::vector indices; ///< Array of vertex indices for triangles }; +/** + * @brief 3D mesh management and rendering class + * + * Handles creation, loading, and rendering of 3D meshes. Supports procedural + * generation of primitive shapes and loading from external files. Manages + * DirectX vertex and index buffers for efficient GPU rendering. + * + * @note All procedural primitives are generated with proper normals and texture coordinates + * @warning Ensure Initialize() is called before creating or loading any mesh data + */ class Mesh { public: + /** + * @brief Default constructor + * + * Initializes member variables to safe default values. + */ Mesh(); + + /** + * @brief Destructor + * + * Automatically calls Shutdown() to ensure proper resource cleanup. + */ ~Mesh(); + /** + * @brief Initialize the mesh system + * + * Sets up the mesh manager with DirectX device and context references + * required for buffer creation and rendering operations. + * + * @param device DirectX 11 device for resource creation + * @param context DirectX 11 device context for rendering operations + * @return HRESULT indicating success or failure of initialization + */ HRESULT Initialize(ID3D11Device* device, ID3D11DeviceContext* context); + + /** + * @brief Clean up all mesh resources + * + * Releases vertex and index buffers and clears mesh data. Safe to call multiple times. + */ void Shutdown(); + /** + * @brief Generate a procedural cube mesh + * + * Creates a cube with 6 faces, proper normals, and texture coordinates. + * + * @param size Edge length of the cube (default: 1.0f) + * @return HRESULT indicating success or failure of mesh creation + */ HRESULT CreateCube(float size = 1.0f); + + /** + * @brief Generate a simple triangle mesh + * + * Creates a single triangle for basic testing and debugging purposes. + * + * @param size Scale factor for the triangle (default: 1.0f) + * @return HRESULT indicating success or failure of mesh creation + */ HRESULT CreateTriangle(float size = 1.0f); + + /** + * @brief Generate a flat plane mesh + * + * Creates a horizontal plane centered at the origin with proper UV mapping. + * + * @param width Width of the plane along X-axis (default: 10.0f) + * @param depth Depth of the plane along Z-axis (default: 10.0f) + * @return HRESULT indicating success or failure of mesh creation + */ HRESULT CreatePlane(float width = 10.0f, float depth = 10.0f); + + /** + * @brief Generate a procedural sphere mesh + * + * Creates a UV sphere using latitude/longitude subdivision with proper + * normals and texture coordinates for seamless texturing. + * + * @param radius Radius of the sphere (default: 1.0f) + * @param slices Number of vertical slices (longitude divisions, default: 20) + * @param stacks Number of horizontal stacks (latitude divisions, default: 20) + * @return HRESULT indicating success or failure of mesh creation + * @note Higher slice/stack values create smoother spheres but increase polygon count + */ HRESULT CreateSphere(float radius = 1.0f, int slices = 20, int stacks = 20); + /** + * @brief Create mesh from custom vertex and index arrays + * + * Allows creation of custom meshes from user-provided vertex and index data. + * + * @param verts Vector of vertices defining the mesh geometry + * @param inds Vector of indices defining triangle connectivity + * @return HRESULT indicating success or failure of mesh creation + */ HRESULT CreateFromVertices(const std::vector& verts, const std::vector& inds); + /** + * @brief Load mesh data from an external file + * + * Loads 3D model data from supported file formats (implementation specific). + * + * @param path File path to the mesh data file + * @return true if loading succeeded, false otherwise + * @note File format support depends on implementation + */ bool LoadFromFile(const std::wstring& path); + /** + * @brief Set the placeholder flag for the mesh + * @param p true to mark as placeholder, false otherwise + */ void SetPlaceholder(bool p) { m_placeholder = p; } + + /** + * @brief Check if this mesh is a placeholder + * @return true if mesh is a placeholder, false otherwise + */ bool IsPlaceholder() const { return m_placeholder; } + /** + * @brief Render the mesh using the provided device context + * + * Binds vertex and index buffers and issues draw calls to render the mesh. + * + * @param ctx DirectX 11 device context for rendering + * @note Shaders must be set before calling this method + */ void Render(ID3D11DeviceContext* ctx); + + /** + * @brief Get the number of vertices in the mesh + * @return Number of vertices + */ UINT GetVertexCount() const { return m_vertexCount; } + + /** + * @brief Get the number of indices in the mesh + * @return Number of indices + */ UINT GetIndexCount() const { return m_indexCount; } private: + /** + * @brief Create DirectX vertex and index buffers from mesh data + * @return HRESULT indicating success or failure of buffer creation + */ HRESULT CreateBuffers(); + + /** + * @brief Calculate vertex normals for the mesh + * + * Computes face normals and averages them for each vertex to provide + * smooth shading across the mesh surface. + */ void CalculateNormals(); - ID3D11Buffer* m_vb{ nullptr }; - ID3D11Buffer* m_ib{ nullptr }; - ID3D11Device* m_device{ nullptr }; - ID3D11DeviceContext* m_context{ nullptr }; + ID3D11Buffer* m_vb{ nullptr }; ///< DirectX vertex buffer + ID3D11Buffer* m_ib{ nullptr }; ///< DirectX index buffer + ID3D11Device* m_device{ nullptr }; ///< DirectX device reference + ID3D11DeviceContext* m_context{ nullptr }; ///< DirectX context reference - std::vector m_vertices; - std::vector m_indices; - unsigned int m_vertexCount{ 0 }; - unsigned int m_indexCount{ 0 }; - bool m_placeholder{ false }; + std::vector m_vertices; ///< CPU vertex data + std::vector m_indices; ///< CPU index data + unsigned int m_vertexCount{ 0 }; ///< Number of vertices + unsigned int m_indexCount{ 0 }; ///< Number of indices + bool m_placeholder{ false }; ///< Placeholder mesh flag }; \ No newline at end of file diff --git a/Spark Engine/Source/Graphics/Shader.h b/Spark Engine/Source/Graphics/Shader.h index d781cd275..db3117f85 100644 --- a/Spark Engine/Source/Graphics/Shader.h +++ b/Spark Engine/Source/Graphics/Shader.h @@ -1,4 +1,14 @@ -// Shader.h +/** + * @file Shader.h + * @brief HLSL shader management and constant buffer handling + * @author Spark Engine Team + * @date 2025 + * + * This class provides a comprehensive shader management system for DirectX 11, + * handling vertex and pixel shader compilation, loading, and constant buffer + * updates for rendering operations in the Spark Engine. + */ + #pragma once #include "Utils/Assert.h" @@ -6,41 +16,134 @@ #include #include -// Constant buffer structure +/** + * @brief Constant buffer structure for shader matrix transformations + * + * Contains the transformation matrices required for vertex shader operations. + * This structure is mapped directly to the constant buffer in HLSL shaders. + */ struct ConstantBuffer { - DirectX::XMMATRIX World; - DirectX::XMMATRIX View; - DirectX::XMMATRIX Projection; + DirectX::XMMATRIX World; ///< World transformation matrix + DirectX::XMMATRIX View; ///< View transformation matrix (camera) + DirectX::XMMATRIX Projection; ///< Projection transformation matrix }; +/** + * @brief HLSL shader management class + * + * Handles loading, compilation, and management of vertex and pixel shaders. + * Also manages constant buffer creation and updates for shader parameters. + * Provides a clean interface for shader operations within the graphics pipeline. + * + * @note Shaders are compiled at runtime from HLSL source files + * @warning Ensure Initialize() is called before loading any shaders + */ class Shader { public: + /** + * @brief Default constructor + * + * Initializes member variables to safe default values. + */ Shader(); + + /** + * @brief Destructor + * + * Automatically calls Shutdown() to ensure proper resource cleanup. + */ ~Shader(); + /** + * @brief Initialize the shader system + * + * Sets up the shader manager with DirectX device and context references. + * Creates the constant buffer for matrix transformations. + * + * @param device DirectX 11 device for resource creation + * @param context DirectX 11 device context for rendering operations + * @return HRESULT indicating success or failure of initialization + */ HRESULT Initialize(ID3D11Device* device, ID3D11DeviceContext* context); + + /** + * @brief Clean up all shader resources + * + * Releases all shader interfaces and buffers. Safe to call multiple times. + */ void Shutdown(); + /** + * @brief Load and compile a vertex shader from file + * + * Compiles an HLSL vertex shader from the specified file and creates + * the corresponding input layout for vertex data. + * + * @param filename Path to the HLSL vertex shader file + * @return HRESULT indicating success or failure of shader loading + * @note The shader must have a "main" entry point + */ HRESULT LoadVertexShader(const std::wstring& filename); + + /** + * @brief Load and compile a pixel shader from file + * + * Compiles an HLSL pixel shader from the specified file. + * + * @param filename Path to the HLSL pixel shader file + * @return HRESULT indicating success or failure of shader loading + * @note The shader must have a "main" entry point + */ HRESULT LoadPixelShader(const std::wstring& filename); + /** + * @brief Bind shaders to the graphics pipeline + * + * Sets the loaded vertex and pixel shaders as active in the rendering pipeline. + * Also sets the input layout for vertex data interpretation. + */ void SetShaders(); + + /** + * @brief Update the constant buffer with new transformation matrices + * + * Updates the shader constant buffer with the provided world, view, and + * projection matrices for the current frame. + * + * @param cb ConstantBuffer structure containing transformation matrices + */ void UpdateConstantBuffer(const ConstantBuffer& cb); + /** + * @brief Compile a shader from an HLSL source file + * + * Static utility function for compiling HLSL shaders from file. + * Used internally but exposed for external shader compilation needs. + * + * @param filename Path to the HLSL shader file + * @param entryPoint Entry point function name (typically "main") + * @param shaderModel Shader model version (e.g., "vs_5_0", "ps_5_0") + * @param blobOut Output parameter for compiled shader bytecode + * @return HRESULT indicating success or failure of compilation + */ static HRESULT CompileShaderFromFile(const std::wstring& filename, const std::string& entryPoint, const std::string& shaderModel, ID3DBlob** blobOut); private: + /** + * @brief Create the constant buffer for transformation matrices + * @return HRESULT indicating success or failure of buffer creation + */ HRESULT CreateConstantBuffer(); - ID3D11Device* m_device{ nullptr }; - ID3D11DeviceContext* m_context{ nullptr }; - ID3D11VertexShader* m_vertexShader{ nullptr }; - ID3D11PixelShader* m_pixelShader{ nullptr }; - ID3D11InputLayout* m_inputLayout{ nullptr }; - ID3D11Buffer* m_constantBuffer{ nullptr }; + ID3D11Device* m_device{ nullptr }; ///< DirectX 11 device reference + ID3D11DeviceContext* m_context{ nullptr }; ///< DirectX 11 context reference + ID3D11VertexShader* m_vertexShader{ nullptr }; ///< Loaded vertex shader + ID3D11PixelShader* m_pixelShader{ nullptr }; ///< Loaded pixel shader + ID3D11InputLayout* m_inputLayout{ nullptr }; ///< Vertex input layout + ID3D11Buffer* m_constantBuffer{ nullptr }; ///< Constant buffer for transformations }; \ No newline at end of file diff --git a/Spark Engine/Source/Input/InputManager.h b/Spark Engine/Source/Input/InputManager.h index 0b2adffd2..1e2c59521 100644 --- a/Spark Engine/Source/Input/InputManager.h +++ b/Spark Engine/Source/Input/InputManager.h @@ -1,52 +1,246 @@ -// InputManager.h +/** + * @file InputManager.h + * @brief Comprehensive input handling system for keyboard and mouse + * @author Spark Engine Team + * @date 2025 + * + * The InputManager class provides a complete input handling system that processes + * keyboard and mouse input events, tracks button states, calculates mouse movement + * deltas, and provides convenient query methods for input state. It supports + * mouse capture for first-person camera controls and maintains both current and + * previous frame states for edge detection. + */ + #pragma once #include "Utils/Assert.h" #include "..\Core\framework.h" #include +/** + * @brief Input management system for keyboard and mouse + * + * The InputManager class handles all user input processing for the Spark Engine. + * It processes Windows messages for keyboard and mouse events, maintains state + * tracking for input queries, and provides mouse capture functionality for + * first-person controls. + * + * Features include: + * - Keyboard state tracking with press/release detection + * - Mouse button state tracking with press/release detection + * - Mouse position and delta movement tracking + * - Mouse capture/release for camera controls + * - Frame-based state management for edge detection + * - Windows message handling integration + * + * @note Input states are updated once per frame via Update() + * @warning Initialize() must be called with a valid window handle before use + */ class InputManager { private: - std::unordered_map m_keyStates; - std::unordered_map m_prevKeyStates; + std::unordered_map m_keyStates; ///< Current frame keyboard states + std::unordered_map m_prevKeyStates; ///< Previous frame keyboard states - bool m_mouseButtons[3]; // Left, Right, Middle - bool m_prevMouseButtons[3]; + bool m_mouseButtons[3]; ///< Current frame mouse button states [Left, Right, Middle] + bool m_prevMouseButtons[3]; ///< Previous frame mouse button states - int m_mouseX, m_mouseY; - int m_prevMouseX, m_prevMouseY; - int m_mouseDeltaX, m_mouseDeltaY; + int m_mouseX, m_mouseY; ///< Current mouse position + int m_prevMouseX, m_prevMouseY; ///< Previous frame mouse position + int m_mouseDeltaX, m_mouseDeltaY; ///< Mouse movement delta since last frame - HWND m_hwnd; - bool m_mouseCaptured; + HWND m_hwnd; ///< Window handle for mouse capture + bool m_mouseCaptured; ///< Whether mouse is currently captured public: + /** + * @brief Default constructor + * + * Initializes input manager with default values. Call Initialize() + * before processing any input. + */ InputManager(); + + /** + * @brief Destructor + * + * Automatically releases mouse capture if it was active. + */ ~InputManager(); + /** + * @brief Initialize the input manager with window handle + * + * Sets up the input manager with the specified window handle for + * mouse capture functionality and input processing. + * + * @param hwnd Handle to the window that will receive input + */ void Initialize(HWND hwnd); + + /** + * @brief Update input states for the current frame + * + * Processes accumulated input changes and updates state tracking. + * Should be called once per frame before querying input states. + * Stores current states as previous states for next frame. + */ void Update(); + + /** + * @brief Process Windows input messages + * + * Handles WM_KEYDOWN, WM_KEYUP, WM_LBUTTONDOWN, WM_LBUTTONUP, + * WM_RBUTTONDOWN, WM_RBUTTONUP, WM_MBUTTONDOWN, WM_MBUTTONUP, + * and WM_MOUSEMOVE messages to update input states. + * + * @param message Windows message type + * @param wParam Message-specific parameter (key code, etc.) + * @param lParam Message-specific parameter (mouse coordinates, etc.) + */ void HandleMessage(UINT message, WPARAM wParam, LPARAM lParam); - // Keyboard + /** + * @brief Check if a key is currently pressed + * + * Returns true if the specified key is currently being held down. + * + * @param key Virtual key code (e.g., VK_SPACE, 'W', VK_ESCAPE) + * @return true if key is currently pressed, false otherwise + */ bool IsKeyDown(int key) const; + + /** + * @brief Check if a key is currently released + * + * Returns true if the specified key is currently not being pressed. + * + * @param key Virtual key code (e.g., VK_SPACE, 'W', VK_ESCAPE) + * @return true if key is currently not pressed, false otherwise + */ bool IsKeyUp(int key) const; + + /** + * @brief Check if a key was just pressed this frame + * + * Returns true if the key was released last frame and pressed this frame. + * Useful for detecting single key press events. + * + * @param key Virtual key code (e.g., VK_SPACE, 'W', VK_ESCAPE) + * @return true if key was just pressed, false otherwise + */ bool WasKeyPressed(int key) const; + + /** + * @brief Check if a key was just released this frame + * + * Returns true if the key was pressed last frame and released this frame. + * Useful for detecting single key release events. + * + * @param key Virtual key code (e.g., VK_SPACE, 'W', VK_ESCAPE) + * @return true if key was just released, false otherwise + */ bool WasKeyReleased(int key) const; - // Mouse + /** + * @brief Check if a mouse button is currently pressed + * + * Returns true if the specified mouse button is currently being held down. + * + * @param button Mouse button index (0=Left, 1=Right, 2=Middle) + * @return true if mouse button is currently pressed, false otherwise + */ bool IsMouseButtonDown(int button) const; + + /** + * @brief Check if a mouse button was just pressed this frame + * + * Returns true if the button was released last frame and pressed this frame. + * + * @param button Mouse button index (0=Left, 1=Right, 2=Middle) + * @return true if mouse button was just pressed, false otherwise + */ bool WasMouseButtonPressed(int button) const; + + /** + * @brief Check if a mouse button was just released this frame + * + * Returns true if the button was pressed last frame and released this frame. + * + * @param button Mouse button index (0=Left, 1=Right, 2=Middle) + * @return true if mouse button was just released, false otherwise + */ bool WasMouseButtonReleased(int button) const; + + /** + * @brief Get mouse movement delta since last frame + * + * Returns the pixel delta movement of the mouse cursor since the last frame. + * Useful for camera controls and mouse look functionality. + * + * @param deltaX Output parameter for horizontal mouse movement + * @param deltaY Output parameter for vertical mouse movement + * @return true if delta values are valid, false otherwise + */ bool GetMouseDelta(int& deltaX, int& deltaY) const; + + /** + * @brief Get current mouse cursor position + * + * Returns the current pixel coordinates of the mouse cursor relative + * to the client area of the window. + * + * @param x Output parameter for horizontal cursor position + * @param y Output parameter for vertical cursor position + */ void GetMousePosition(int& x, int& y) const; + /** + * @brief Capture or release the mouse cursor + * + * When captured, the mouse cursor is hidden and confined to the window, + * and movement generates delta values for camera controls. When released, + * the cursor becomes visible and can move freely. + * + * @param capture true to capture mouse, false to release + */ void CaptureMouse(bool capture); + + /** + * @brief Check if the mouse is currently captured + * @return true if mouse is captured, false if free + */ bool IsMouseCaptured() const { return m_mouseCaptured; } private: + /** + * @brief Update the state of a specific key + * + * Internal method for updating keyboard state from Windows messages. + * + * @param key Virtual key code to update + * @param isDown true if key is pressed, false if released + */ void UpdateKeyState(int key, bool isDown); + + /** + * @brief Update the state of a specific mouse button + * + * Internal method for updating mouse button state from Windows messages. + * + * @param button Mouse button index (0=Left, 1=Right, 2=Middle) + * @param isDown true if button is pressed, false if released + */ void UpdateMouseButton(int button, bool isDown); + + /** + * @brief Update mouse position and calculate delta + * + * Internal method for updating mouse position from Windows messages + * and calculating movement delta. + * + * @param x New horizontal mouse position + * @param y New vertical mouse position + */ void UpdateMousePosition(int x, int y); }; \ No newline at end of file diff --git a/Spark Engine/Source/Physics/CollisionSystem.h b/Spark Engine/Source/Physics/CollisionSystem.h index c1d33b39b..c907c13b3 100644 --- a/Spark Engine/Source/Physics/CollisionSystem.h +++ b/Spark Engine/Source/Physics/CollisionSystem.h @@ -1,4 +1,15 @@ -// CollisionSystem.h +/** + * @file CollisionSystem.h + * @brief Comprehensive 3D collision detection and physics system + * @author Spark Engine Team + * @date 2025 + * + * This file provides a complete collision detection system with primitive shapes, + * raycast functionality, contact resolution, and utility functions for 3D physics + * calculations. The system supports sphere, box, and ray-based collision queries + * with detailed collision information and contact manifolds. + */ + #pragma once #include "Utils/Assert.h" @@ -11,52 +22,127 @@ using DirectX::XMFLOAT3; using DirectX::XMMATRIX; -// Bounding box +/** + * @brief Axis-aligned bounding box for collision detection + * + * Represents a 3D bounding box defined by minimum and maximum corner points. + * Used for efficient collision detection and spatial partitioning. + */ struct BoundingBox { - XMFLOAT3 Min; - XMFLOAT3 Max; + XMFLOAT3 Min; ///< Minimum corner of the bounding box + XMFLOAT3 Max; ///< Maximum corner of the bounding box + /** + * @brief Default constructor creating a unit box centered at origin + */ BoundingBox() : Min(-1, -1, -1), Max(1, 1, 1) {} + + /** + * @brief Constructor with explicit min/max corners + * @param min Minimum corner point + * @param max Maximum corner point + */ BoundingBox(const XMFLOAT3& min, const XMFLOAT3& max) : Min(min), Max(max) {} + /** + * @brief Get the center point of the bounding box + * @return Center point coordinates + */ XMFLOAT3 GetCenter() const; + + /** + * @brief Get the extents (half-sizes) of the bounding box + * @return Extents from center to edges along each axis + */ XMFLOAT3 GetExtents() const; + + /** + * @brief Transform the bounding box by a matrix + * @param transform 4x4 transformation matrix to apply + */ void Transform(const XMMATRIX& transform); }; -// Bounding sphere +/** + * @brief Bounding sphere for collision detection + * + * Represents a 3D sphere defined by center point and radius. + * Often used for fast collision detection due to simple math. + */ struct BoundingSphere { - XMFLOAT3 Center; - float Radius; + XMFLOAT3 Center; ///< Center point of the sphere + float Radius; ///< Radius of the sphere + /** + * @brief Default constructor creating a unit sphere at origin + */ BoundingSphere() : Center(0, 0, 0), Radius(1) {} + + /** + * @brief Constructor with explicit center and radius + * @param c Center point of the sphere + * @param r Radius of the sphere + */ BoundingSphere(const XMFLOAT3& c, float r) : Center(c), Radius(r) {} + /** + * @brief Transform the bounding sphere by a matrix + * @param transform 4x4 transformation matrix to apply + * @note Only uniform scaling is properly supported for spheres + */ void Transform(const XMMATRIX& transform); }; -// Ray +/** + * @brief 3D ray for raycasting operations + * + * Represents a ray with an origin point and direction vector. + * Used for collision detection, picking, and line-of-sight queries. + */ struct Ray { - XMFLOAT3 Origin; - XMFLOAT3 Direction; + XMFLOAT3 Origin; ///< Starting point of the ray + XMFLOAT3 Direction; ///< Direction vector of the ray (should be normalized) + /** + * @brief Default constructor creating a ray along positive Z-axis + */ Ray() : Origin(0, 0, 0), Direction(0, 0, 1) {} + + /** + * @brief Constructor with explicit origin and direction + * @param o Origin point of the ray + * @param d Direction vector of the ray + */ Ray(const XMFLOAT3& o, const XMFLOAT3& d) : Origin(o), Direction(d) {} + /** + * @brief Get a point along the ray at parameter t + * @param t Distance parameter along the ray + * @return Point at position Origin + t * Direction + */ XMFLOAT3 GetPoint(float t) const; }; -// Contact manifold +/** + * @brief Contact manifold for collision resolution + * + * Contains detailed information about a collision including contact points, + * surface normal, and penetration depth. Used for physics response and + * collision resolution calculations. + */ struct ContactManifold { - XMFLOAT3 ContactPoints[4]; - XMFLOAT3 Normal; - float PenetrationDepth; - int ContactCount; + XMFLOAT3 ContactPoints[4]; ///< Up to 4 contact points for stable collision resolution + XMFLOAT3 Normal; ///< Surface normal at the collision point + float PenetrationDepth; ///< How deep objects are interpenetrating + int ContactCount; ///< Number of valid contact points (0-4) + /** + * @brief Default constructor with safe initial values + */ ContactManifold() : Normal(0, 1, 0), PenetrationDepth(0), ContactCount(0) { @@ -65,50 +151,209 @@ struct ContactManifold } }; -// Raycast result +/** + * @brief Result of a raycast collision query + * + * Contains all information about a ray-object intersection including + * hit status, contact point, surface normal, distance, and optional user data. + */ struct CollisionResult { - bool Hit; - XMFLOAT3 Point; - XMFLOAT3 Normal; - float Distance; - void* UserData; + bool Hit; ///< Whether the ray hit the object + XMFLOAT3 Point; ///< World position of the intersection point + XMFLOAT3 Normal; ///< Surface normal at the intersection point + float Distance; ///< Distance from ray origin to intersection point + void* UserData; ///< Optional pointer to additional collision data + /** + * @brief Default constructor indicating no collision + */ CollisionResult() : Hit(false), Point(0, 0, 0), Normal(0, 1, 0), Distance(0), UserData(nullptr) { } }; +/** + * @brief Static collision detection and physics utility class + * + * The CollisionSystem provides a comprehensive set of static methods for + * performing various types of collision detection queries. It supports + * primitive-vs-primitive tests, ray casting, and utility functions for + * 3D vector mathematics and geometric calculations. + * + * Features include: + * - Sphere-sphere, sphere-box, and box-box collision detection + * - Ray-casting against spheres, boxes, planes, and triangles + * - Contact manifold generation for physics response + * - Point-in-shape queries for spatial testing + * - Vector mathematics utilities for 3D calculations + * + * @note All methods are static and thread-safe + * @warning Ensure all input vectors are valid (no NaN or infinite values) + */ class CollisionSystem { public: - // Primitive tests + /** + * @brief Test collision between two spheres + * @param a First bounding sphere + * @param b Second bounding sphere + * @return true if spheres are overlapping, false otherwise + */ static bool SphereVsSphere(const BoundingSphere& a, const BoundingSphere& b); + + /** + * @brief Test collision between two spheres with contact manifold + * @param a First bounding sphere + * @param b Second bounding sphere + * @param m Output contact manifold with collision details + * @return true if spheres are overlapping, false otherwise + */ static bool SphereVsSphere(const BoundingSphere& a, const BoundingSphere& b, ContactManifold& m); + + /** + * @brief Test collision between sphere and axis-aligned box + * @param sphere Bounding sphere to test + * @param box Bounding box to test + * @return true if sphere and box are overlapping, false otherwise + */ static bool SphereVsBox(const BoundingSphere& sphere, const BoundingBox& box); + + /** + * @brief Test collision between two axis-aligned boxes + * @param a First bounding box + * @param b Second bounding box + * @return true if boxes are overlapping, false otherwise + */ static bool BoxVsBox(const BoundingBox& a, const BoundingBox& b); - // Ray tests + /** + * @brief Cast a ray against a sphere + * @param ray Ray to cast + * @param sphere Sphere to test against + * @return CollisionResult with hit information + */ static CollisionResult RayVsSphere(const Ray& ray, const BoundingSphere& sphere); + + /** + * @brief Cast a ray against an axis-aligned box + * @param ray Ray to cast + * @param box Box to test against + * @return CollisionResult with hit information + */ static CollisionResult RayVsBox(const Ray& ray, const BoundingBox& box); + + /** + * @brief Cast a ray against an infinite plane + * @param ray Ray to cast + * @param planePoint Any point on the plane + * @param planeNormal Normal vector of the plane (should be normalized) + * @return CollisionResult with hit information + */ static CollisionResult RayVsPlane(const Ray& ray, const XMFLOAT3& planePoint, const XMFLOAT3& planeNormal); + + /** + * @brief Cast a ray against a triangle + * @param ray Ray to cast + * @param v0 First vertex of the triangle + * @param v1 Second vertex of the triangle + * @param v2 Third vertex of the triangle + * @return CollisionResult with hit information + */ static CollisionResult RayVsTriangle(const Ray& ray, const XMFLOAT3& v0, const XMFLOAT3& v1, const XMFLOAT3& v2); - // Utility functions + /** + * @brief Find the closest point on a box to a given point + * @param point Point to find closest position to + * @param box Bounding box to find closest point on + * @return Closest point on the box surface + */ static XMFLOAT3 ClosestPointOnBox(const XMFLOAT3& point, const BoundingBox& box); + + /** + * @brief Find the closest point on a sphere to a given point + * @param point Point to find closest position to + * @param sphere Bounding sphere to find closest point on + * @return Closest point on the sphere surface + */ static XMFLOAT3 ClosestPointOnSphere(const XMFLOAT3& point, const BoundingSphere& sphere); + + /** + * @brief Calculate distance from a point to an infinite plane + * @param point Point to measure distance from + * @param planePoint Any point on the plane + * @param planeNormal Normal vector of the plane (should be normalized) + * @return Signed distance to the plane (positive = in front of normal) + */ static float DistancePointToPlane(const XMFLOAT3& point, const XMFLOAT3& planePoint, const XMFLOAT3& planeNormal); - // Point tests + /** + * @brief Test if a point is inside a sphere + * @param point Point to test + * @param sphere Sphere to test against + * @return true if point is inside sphere, false otherwise + */ static bool PointInSphere(const XMFLOAT3& point, const BoundingSphere& sphere); + + /** + * @brief Test if a point is inside an axis-aligned box + * @param point Point to test + * @param box Box to test against + * @return true if point is inside box, false otherwise + */ static bool PointInBox(const XMFLOAT3& point, const BoundingBox& box); - // Vector helpers + /** + * @brief Calculate the length of a 3D vector + * @param v Vector to calculate length of + * @return Length (magnitude) of the vector + */ static float Vector3Length(const XMFLOAT3& v); + + /** + * @brief Calculate the squared length of a 3D vector + * @param v Vector to calculate squared length of + * @return Squared length of the vector (avoids sqrt for performance) + */ static float Vector3LengthSquared(const XMFLOAT3& v); + + /** + * @brief Normalize a 3D vector to unit length + * @param v Vector to normalize + * @return Normalized vector with length 1.0 + */ static XMFLOAT3 Vector3Normalize(const XMFLOAT3& v); + + /** + * @brief Calculate the dot product of two 3D vectors + * @param a First vector + * @param b Second vector + * @return Dot product (scalar result) + */ static float Vector3Dot(const XMFLOAT3& a, const XMFLOAT3& b); + + /** + * @brief Calculate the cross product of two 3D vectors + * @param a First vector + * @param b Second vector + * @return Cross product vector perpendicular to both inputs + */ static XMFLOAT3 Vector3Cross(const XMFLOAT3& a, const XMFLOAT3& b); + + /** + * @brief Reflect a vector off a surface normal + * @param i Incident vector + * @param n Surface normal (should be normalized) + * @return Reflected vector + */ static XMFLOAT3 Vector3Reflect(const XMFLOAT3& i, const XMFLOAT3& n); + + /** + * @brief Linear interpolation between two 3D vectors + * @param a Start vector + * @param b End vector + * @param t Interpolation parameter (0.0 = a, 1.0 = b) + * @return Interpolated vector + */ static XMFLOAT3 Vector3Lerp(const XMFLOAT3& a, const XMFLOAT3& b, float t); }; \ No newline at end of file diff --git a/Spark Engine/Source/Projectiles/Projectile.h b/Spark Engine/Source/Projectiles/Projectile.h index 3043cba2f..1e5435b3c 100644 --- a/Spark Engine/Source/Projectiles/Projectile.h +++ b/Spark Engine/Source/Projectiles/Projectile.h @@ -1,4 +1,14 @@ -// Projectile.h +/** + * @file Projectile.h + * @brief Base class for all projectile objects in the game + * @author Spark Engine Team + * @date 2025 + * + * This class provides the fundamental functionality for projectile objects including + * physics simulation, collision detection, lifetime management, and rendering. + * All specific projectile types (bullets, rockets, grenades) inherit from this base class. + */ + #pragma once #include "..\Core\framework.h" // XMFLOAT3, XMMATRIX, HRESULT @@ -6,60 +16,179 @@ #include "..\Game\GameObject.h" #include "Utils/Assert.h" +/** + * @brief Base class for all projectile objects + * + * The Projectile class provides the core functionality needed by all projectile + * types in the game. It handles physics simulation, collision detection, lifetime + * management, and basic rendering. Derived classes implement specific behaviors + * for different projectile types like bullets, rockets, and grenades. + * + * Features include: + * - Physics-based movement with velocity and optional gravity + * - Collision detection using bounding spheres + * - Automatic lifetime management and deactivation + * - Damage system integration + * - Object pooling support for performance + * + * @note This class inherits from GameObject and implements the collision callbacks + * @warning Derived classes should call the base class methods when overriding + */ class Projectile : public GameObject { protected: // Motion - DirectX::XMFLOAT3 m_velocity; - float m_speed; - float m_lifeTime; - float m_maxLifeTime; - float m_damage; - bool m_active; + DirectX::XMFLOAT3 m_velocity; ///< Current velocity vector + float m_speed; ///< Base speed magnitude + float m_lifeTime; ///< Current lifetime counter + float m_maxLifeTime; ///< Maximum lifetime before auto-deactivation + float m_damage; ///< Damage dealt to targets + bool m_active; ///< Whether projectile is currently active // Physics - BoundingSphere m_boundingSphere; - bool m_hasGravity; - float m_gravityScale; + BoundingSphere m_boundingSphere; ///< Collision bounds + bool m_hasGravity; ///< Whether gravity affects this projectile + float m_gravityScale; ///< Multiplier for gravity effect public: + /** + * @brief Default constructor + * + * Initializes projectile with default values suitable for most projectile types. + */ Projectile(); + + /** + * @brief Virtual destructor for proper polymorphic cleanup + */ ~Projectile() override; - // GameObject overrides + /** + * @brief Initialize the projectile with DirectX resources + * @param device DirectX 11 device for resource creation + * @param context DirectX 11 device context for rendering + * @return HRESULT indicating success or failure + */ HRESULT Initialize(ID3D11Device* device, ID3D11DeviceContext* context) override; + + /** + * @brief Update projectile physics and lifetime + * @param deltaTime Time elapsed since last frame in seconds + */ void Update(float deltaTime) override; + + /** + * @brief Render the projectile + * @param view Camera view matrix + * @param projection Camera projection matrix + */ void Render(const DirectX::XMMATRIX& view, const DirectX::XMMATRIX& projection) override; - // Projectile actions + /** + * @brief Fire the projectile with initial parameters + * @param startPosition World position to start from + * @param direction Normalized direction vector + * @param speed Initial speed magnitude + */ void Fire(const DirectX::XMFLOAT3& startPosition, const DirectX::XMFLOAT3& direction, float speed); + + /** + * @brief Deactivate the projectile for object pool return + */ void Deactivate(); + + /** + * @brief Reset projectile state for reuse + */ void Reset(); - // Collision callbacks + /** + * @brief Collision callback when projectile hits another object + * @param target Pointer to the hit game object + */ void OnHit(GameObject* target) override; + + /** + * @brief Collision callback when projectile hits world geometry + * @param hitPoint World position of collision + * @param normal Surface normal at collision point + */ void OnHitWorld(const DirectX::XMFLOAT3& hitPoint, const DirectX::XMFLOAT3& normal) override; - // Physics controls + /** + * @brief Configure gravity settings for the projectile + * @param enabled Whether gravity should affect this projectile + * @param scale Gravity scale multiplier (default: 1.0) + */ void SetGravity(bool enabled, float scale = 1.0f); + + /** + * @brief Apply an external force to the projectile + * @param force Force vector to apply + */ void ApplyForce(const DirectX::XMFLOAT3& force); - // Accessors + /** + * @brief Check if projectile is currently active + * @return true if active, false if available for reuse + */ bool IsActive() const { return m_active; } + + /** + * @brief Get the damage value of this projectile + * @return Damage amount + */ float GetDamage() const { return m_damage; } + + /** + * @brief Get the current velocity vector + * @return Current velocity + */ const DirectX::XMFLOAT3& GetVelocity() const { return m_velocity; } + + /** + * @brief Get the collision bounding sphere + * @return Bounding sphere for collision detection + */ const BoundingSphere& GetBoundingSphere() const { return m_boundingSphere; } + /** + * @brief Set the damage amount + * @param damage New damage value (must be non-negative) + */ void SetDamage(float damage) { ASSERT_MSG(damage >= 0, "Damage must be non-negative"); m_damage = damage; } + + /** + * @brief Set the maximum lifetime + * @param lifeTime New lifetime in seconds (must be positive) + */ void SetLifeTime(float lifeTime) { ASSERT_MSG(lifeTime > 0, "LifeTime must be positive"); m_maxLifeTime = lifeTime; } protected: - // Internal helpers + /** + * @brief Create the mesh for this projectile type + * + * Virtual method that derived classes should override to create + * their specific mesh geometry. + */ void CreateMesh() override; + + /** + * @brief Check for collisions with world and other objects + */ void CheckCollisions(); + + /** + * @brief Update physics simulation + * @param deltaTime Time step for physics integration + */ void UpdatePhysics(float deltaTime); + + /** + * @brief Update the bounding sphere position + */ void UpdateBoundingSphere(); }; \ No newline at end of file diff --git a/Spark Engine/Source/Projectiles/ProjectilePool.h b/Spark Engine/Source/Projectiles/ProjectilePool.h index 329b66e4b..517b0eea9 100644 --- a/Spark Engine/Source/Projectiles/ProjectilePool.h +++ b/Spark Engine/Source/Projectiles/ProjectilePool.h @@ -1,4 +1,14 @@ -// ProjectilePool.h +/** + * @file ProjectilePool.h + * @brief Object pool system for efficient projectile management + * @author Spark Engine Team + * @date 2025 + * + * This class provides an efficient object pool for managing projectiles to avoid + * frequent memory allocations and deallocations during gameplay. It supports + * multiple projectile types and provides convenient firing methods. + */ + #pragma once #include "Utils/Assert.h" @@ -9,41 +19,138 @@ #include #include "Projectile.h" +/** + * @brief Enumeration of projectile types for factory creation + */ enum class ProjectileType { - BULLET, - ROCKET, - GRENADE + BULLET, ///< Fast, small projectiles for rifles and pistols + ROCKET, ///< Explosive projectiles with area damage + GRENADE ///< Lobbed explosive projectiles with gravity }; +/** + * @brief Object pool for efficient projectile management + * + * The ProjectilePool manages a fixed pool of projectile objects to avoid + * memory allocation overhead during gameplay. It handles creation, updating, + * rendering, and recycling of projectiles automatically. + * + * Features include: + * - Pre-allocated pool of reusable projectile objects + * - Factory methods for different projectile types + * - Automatic lifecycle management + * - Performance tracking with active/available counts + * + * @note Pool size should be large enough to handle peak projectile usage + * @warning Initialize() must be called before firing any projectiles + */ class ProjectilePool { public: + /** + * @brief Constructor with pool size specification + * @param poolSize Maximum number of simultaneous projectiles + */ ProjectilePool(size_t poolSize); + + /** + * @brief Destructor automatically cleans up all projectiles + */ ~ProjectilePool(); + /** + * @brief Initialize the projectile pool with DirectX resources + * @param device DirectX 11 device for projectile creation + * @param context DirectX 11 device context for rendering + * @return HRESULT indicating success or failure + */ HRESULT Initialize(ID3D11Device* device, ID3D11DeviceContext* context); + + /** + * @brief Update all active projectiles + * @param deltaTime Time elapsed since last frame in seconds + */ void Update(float deltaTime); + + /** + * @brief Render all active projectiles + * @param view Camera view matrix + * @param proj Camera projection matrix + */ void Render(const DirectX::XMMATRIX& view, const DirectX::XMMATRIX& proj); + + /** + * @brief Shutdown and clean up all resources + */ void Shutdown(); + /** + * @brief Get an available projectile from the pool + * @return Pointer to available projectile, or nullptr if pool is full + */ Projectile* GetProjectile(); + + /** + * @brief Return a projectile to the available pool + * @param p Pointer to the projectile to return + */ void ReturnProjectile(Projectile* p); + /** + * @brief Fire a bullet projectile + * @param pos Starting position + * @param dir Direction vector (should be normalized) + * @param speed Initial speed + */ void FireBullet(const DirectX::XMFLOAT3& pos, const DirectX::XMFLOAT3& dir, float speed); + + /** + * @brief Fire a rocket projectile + * @param pos Starting position + * @param dir Direction vector (should be normalized) + * @param speed Initial speed + */ void FireRocket(const DirectX::XMFLOAT3& pos, const DirectX::XMFLOAT3& dir, float speed); + + /** + * @brief Fire a grenade projectile + * @param pos Starting position + * @param dir Direction vector (should be normalized) + * @param speed Initial speed + */ void FireGrenade(const DirectX::XMFLOAT3& pos, const DirectX::XMFLOAT3& dir, float speed); + + /** + * @brief Fire a projectile of specified type + * @param type Type of projectile to fire + * @param pos Starting position + * @param dir Direction vector (should be normalized) + * @param speed Initial speed + */ void FireProjectile(ProjectileType type, const DirectX::XMFLOAT3& pos, const DirectX::XMFLOAT3& dir, float speed); + /** + * @brief Get the number of currently active projectiles + * @return Number of projectiles in use + */ size_t GetActiveCount() const; + + /** + * @brief Get the number of available projectiles in the pool + * @return Number of projectiles available for use + */ size_t GetAvailableCount() const; private: + /** + * @brief Create all projectile objects for the pool + */ void CreateProjectiles(); - size_t m_poolSize; - ID3D11Device* m_device; - ID3D11DeviceContext* m_context; - std::vector> m_projectiles; - std::queue m_availableProjectiles; + size_t m_poolSize; ///< Maximum pool size + ID3D11Device* m_device; ///< DirectX device reference + ID3D11DeviceContext* m_context; ///< DirectX context reference + std::vector> m_projectiles; ///< All projectile objects + std::queue m_availableProjectiles; ///< Queue of available projectiles }; \ No newline at end of file diff --git a/Spark Engine/Source/Projectiles/WeaponStats.h b/Spark Engine/Source/Projectiles/WeaponStats.h index a58c9ecb8..0b43dae9e 100644 --- a/Spark Engine/Source/Projectiles/WeaponStats.h +++ b/Spark Engine/Source/Projectiles/WeaponStats.h @@ -1,29 +1,52 @@ -// WeaponStats.h +/** + * @file WeaponStats.h + * @brief Weapon configuration and statistics system + * @author Spark Engine Team + * @date 2025 + * + * This file defines weapon types, statistics structures, and default configurations + * for the weapon system. It provides a data-driven approach to weapon balancing + * and configuration management. + */ + #pragma once #include "Utils/Assert.h" -// Supported weapon types +/** + * @brief Enumeration of supported weapon types + * + * Defines the different categories of weapons available in the game. + * Each type has associated default statistics and behaviors. + */ enum class WeaponType { - PISTOL, - RIFLE, - SHOTGUN, - ROCKET_LAUNCHER, - GRENADE_LAUNCHER + PISTOL, ///< Semi-automatic pistol with moderate damage and high accuracy + RIFLE, ///< Automatic rifle with high damage and moderate accuracy + SHOTGUN, ///< Close-range weapon with high damage but low accuracy + ROCKET_LAUNCHER, ///< Explosive weapon with very high damage but slow fire rate + GRENADE_LAUNCHER ///< Area-of-effect weapon with explosive projectiles }; -// Stats for each weapon +/** + * @brief Weapon statistics and configuration structure + * + * Contains all the parameters that define a weapon's behavior including + * damage, fire rate, ammunition, and ballistic properties. + */ struct WeaponStats { - WeaponType Type; // Weapon category - float Damage; // Damage per shot - float FireRate; // Rounds per minute - int MagazineSize; // Rounds per magazine - float ReloadTime; // Seconds to reload - float MuzzleVelocity; // Projectile speed (units/sec) - float Accuracy; // [0.0f .. 1.0f], higher is more accurate + WeaponType Type; ///< Weapon category/type + float Damage; ///< Base damage per shot/projectile + float FireRate; ///< Rate of fire in rounds per minute + int MagazineSize; ///< Number of rounds per magazine/clip + float ReloadTime; ///< Time required to reload in seconds + float MuzzleVelocity; ///< Initial projectile speed in units per second + float Accuracy; ///< Accuracy factor (0.0 = completely inaccurate, 1.0 = perfect accuracy) + /** + * @brief Default constructor with safe initial values + */ WeaponStats() : Type(WeaponType::PISTOL) , Damage(0.0f) @@ -36,7 +59,18 @@ struct WeaponStats } }; -// Helper to retrieve default stats for each weapon type +/** + * @brief Get default weapon statistics for a specific weapon type + * + * Returns pre-configured weapon statistics for each weapon type with + * balanced values suitable for gameplay. These can be used as baseline + * values and modified as needed for game balancing. + * + * @param type The weapon type to get default stats for + * @return WeaponStats structure with default values for the specified type + * @note Values are balanced for typical FPS gameplay scenarios + * @warning Will assert if an unknown weapon type is provided + */ inline WeaponStats GetDefaultWeaponStats(WeaponType type) { WeaponStats stats; @@ -46,47 +80,47 @@ inline WeaponStats GetDefaultWeaponStats(WeaponType type) { case WeaponType::PISTOL: stats.Damage = 25.0f; - stats.FireRate = 300.0f; + stats.FireRate = 300.0f; // 5 shots per second stats.MagazineSize = 12; stats.ReloadTime = 1.5f; stats.MuzzleVelocity = 300.0f; - stats.Accuracy = 0.95f; + stats.Accuracy = 0.95f; // Very accurate break; case WeaponType::RIFLE: stats.Damage = 35.0f; - stats.FireRate = 600.0f; + stats.FireRate = 600.0f; // 10 shots per second stats.MagazineSize = 30; stats.ReloadTime = 2.5f; stats.MuzzleVelocity = 800.0f; - stats.Accuracy = 0.85f; + stats.Accuracy = 0.85f; // Good accuracy break; case WeaponType::SHOTGUN: stats.Damage = 60.0f; - stats.FireRate = 120.0f; + stats.FireRate = 120.0f; // 2 shots per second stats.MagazineSize = 8; stats.ReloadTime = 3.0f; stats.MuzzleVelocity = 400.0f; - stats.Accuracy = 0.60f; + stats.Accuracy = 0.60f; // Lower accuracy, spread pattern break; case WeaponType::ROCKET_LAUNCHER: stats.Damage = 150.0f; - stats.FireRate = 60.0f; + stats.FireRate = 60.0f; // 1 shot per second stats.MagazineSize = 4; stats.ReloadTime = 4.0f; stats.MuzzleVelocity = 200.0f; - stats.Accuracy = 1.00f; + stats.Accuracy = 1.00f; // Perfect accuracy break; case WeaponType::GRENADE_LAUNCHER: stats.Damage = 100.0f; - stats.FireRate = 90.0f; + stats.FireRate = 90.0f; // 1.5 shots per second stats.MagazineSize = 6; stats.ReloadTime = 3.5f; stats.MuzzleVelocity = 150.0f; - stats.Accuracy = 0.90f; + stats.Accuracy = 0.90f; // High accuracy break; default: diff --git a/Spark Engine/Source/Utils/Timer.h b/Spark Engine/Source/Utils/Timer.h index 832df5089..2fc0d07c8 100644 --- a/Spark Engine/Source/Utils/Timer.h +++ b/Spark Engine/Source/Utils/Timer.h @@ -1,30 +1,118 @@ -// Timer.h +/** + * @file Timer.h + * @brief High-precision timing system for frame rate and delta time calculation + * @author Spark Engine Team + * @date 2025 + * + * This class provides a high-precision timing system using the system's high-resolution + * clock for accurate frame timing, delta time calculation, and total elapsed time tracking. + * Essential for frame-rate independent game logic and performance measurement. + */ + #pragma once #include "..\Core\framework.h" #include "Utils/Assert.h" #include +/** + * @brief High-precision timer for game engine timing + * + * The Timer class provides accurate timing functionality for game engines using + * the system's high-resolution clock. It tracks delta time between frames and + * total elapsed time, supporting pause/resume functionality for game state management. + * + * Features include: + * - High-precision timing using std::chrono::high_resolution_clock + * - Delta time calculation for frame-rate independent updates + * - Total elapsed time tracking + * - Pause/resume functionality + * - Automatic time tracking with simple interface + * + * @note Delta time is calculated between consecutive calls to GetDeltaTime() + * @warning Ensure Start() is called before using timing functions + */ class Timer { private: - std::chrono::high_resolution_clock::time_point m_lastTime; - float m_deltaTime; - float m_totalTime; - bool m_paused; + std::chrono::high_resolution_clock::time_point m_lastTime; ///< Time point of last measurement + float m_deltaTime; ///< Time elapsed since last frame in seconds + float m_totalTime; ///< Total elapsed time since start in seconds + bool m_paused; ///< Whether the timer is currently paused public: + /** + * @brief Default constructor + * + * Initializes timer with zero values and stopped state. + * Call Start() to begin timing operations. + */ Timer(); + + /** + * @brief Destructor + * + * Automatically stops the timer if it was running. + */ ~Timer(); + /** + * @brief Start or resume the timer + * + * Begins timing operations or resumes from a paused state. + * Records the current time as the reference point for delta calculations. + */ void Start(); + + /** + * @brief Pause the timer + * + * Stops time accumulation while preserving current state. + * Can be resumed with Start(). + */ void Stop(); + + /** + * @brief Reset timer to initial state + * + * Resets total time to zero and stops the timer. + * Must call Start() again to resume timing. + */ void Reset(); + + /** + * @brief Get delta time since last call and update internal time + * + * Returns the time elapsed since the last call to this method and + * updates the internal timing state for the next call. + * + * @return Delta time in seconds since last call + * @note Returns 0.0 if timer is paused + */ float GetDeltaTime(); + + /** + * @brief Get total elapsed time since timer start + * + * Returns the cumulative time that has elapsed since the timer + * was started, excluding any time spent in paused state. + * + * @return Total elapsed time in seconds + */ float GetTotalTime() const { return m_totalTime; } + /** + * @brief Check if the timer is currently paused + * @return true if timer is paused, false if running + */ bool IsPaused() const { return m_paused; } private: + /** + * @brief Update internal time tracking + * + * Internal method that calculates delta time and updates total time. + * Called automatically by GetDeltaTime(). + */ void UpdateTime(); }; \ No newline at end of file