repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
mamoniem/bellz
Source/Bellz/Gladiator.h
// All rights reserved, <NAME> 2016 http://www.mamoniem.com/ #pragma once #include "GameDataTables.h" #include "GameFramework/Character.h" #include "Gladiator.generated.h" UCLASS(config = Game) class AGladiator : public ACharacter { GENERATED_BODY() virtual void BeginPlay() override; //Camera boom positioning the camera behind the character UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true")) class USpringArmComponent* CameraBoom; //Follow camera UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true")) class UCameraComponent* FollowCamera; //The sprite used to draw effect, better and more contrallable than using the HUD or Textures UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Effects, meta = (AllowPrivateAccess = "true")) class UPaperSpriteComponent* EffectSprite; public: AGladiator(); //Base turn rate, in deg/sec. Other scaling may affect final turn rate. UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera) float BaseTurnRate; //Base look up/down rate, in deg/sec. Other scaling may affect final rate. UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera) float BaseLookUpRate; //Base Jump velocity UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Player Attributes") float jumppingVelocity; //Is the player dead or not UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Player Attributes") bool IsStillAlive; //is the palyer attacking right now ? UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Player Attributes") bool IsAttacking; //is the palyer attacking right now ? UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Player Attributes") int32 WeaponIndex; //is the palyer attacking right now ? UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Player Collectebles") int32 CollectedCoins; //is the palyer attacking right now ? UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Player Collectebles") int32 CollectedCoinsValue; //To be able to disable the player during cutscenes, menus, death....etc UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Player Collectebles") bool IsControlable; UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Game DataTables") AGameDataTables* TablesInstance; //Return if the player dead or alive UFUNCTION(BlueprintCallable, Category = "Player Attributes") bool GetIsStillAlive() const { return IsStillAlive; } //Enable or disable inputs UFUNCTION(BlueprintCallable, Category = "Player Attributes") void OnSetPlayerController(bool status); //Perform attack UFUNCTION(BlueprintCallable, Category = "Player Attributes") void OnChangeHealthByAmount(float usedAmount); UFUNCTION(BlueprintCallable, Category = "Player Attributes") float OnGetHealthAmount() const {return TotalHealth;} UFUNCTION(BlueprintCallable, Category = "Player Actions") void OnPostAttack(); //Returns CameraBoom subobject FORCEINLINE class USpringArmComponent* GetCameraBoom() const { return CameraBoom; } //Returns FollowCamera subobject FORCEINLINE class UCameraComponent* GetFollowCamera() const { return FollowCamera; } protected: UFUNCTION(BlueprintCallable, Category = "Player Actions") void MoveForward(float Value); UFUNCTION(BlueprintCallable, Category = "Player Actions") void MoveRight(float Value); UFUNCTION(BlueprintCallable, Category = "Player Actions") void Jump(); UFUNCTION(BlueprintCallable, Category = "Player Actions") void StopJumping(); UFUNCTION(BlueprintCallable, Category = "Player Actions") void OnAttack(); UFUNCTION(BlueprintCallable, Category = "Player Actions") void OnChangeWeapon(); //Called via input to turn at a given rate. void TurnAtRate(float Rate); //Called via input to turn look up/down at a given rate. void LookUpAtRate(float Rate); //Called when we collecteing a pickup UFUNCTION(BlueprintCallable, Category = "PickupSystem") void OnCollectPickup(); //The health of the enemy UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Player Attributes") float TotalHealth; //The range for the enemy attack UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Player Attributes") float AttackRange; protected: //APawn interface virtual void SetupPlayerInputComponent(class UInputComponent* InputComponent) override; //End of APawn interface };
mamoniem/bellz
Source/Bellz/BellzSaveGame.h
// All rights reserved, <NAME> 2016 http: #pragma once #include "GameFramework/SaveGame.h" #include "BellzSaveGame.generated.h" /** * */ UCLASS() class BELLZ_API UBellzSaveGame : public USaveGame { GENERATED_BODY() public: UPROPERTY(VisibleAnywhere, Category = SavedValues) FString SlotName; UPROPERTY(VisibleAnywhere, Category = SavedValues) uint32 PlayerIndex; UPROPERTY(VisibleAnywhere, Category = SavedValues) uint32 CollectedCoins; UPROPERTY(VisibleAnywhere, Category = SavedValues) float PlayerHealth; UPROPERTY(VisibleAnywhere, Category = SavedValues) uint32 lastUsedWeaponIndex; UPROPERTY(VisibleAnywhere, Category = SavedValues) FString PlayerName; UBellzSaveGame(); };
brandondixon/uart-message
umsg.c
//***************************************************************************** // // umsg.c - Driver for the UMSG module. // // Copyright (c) 2015 Sevun Scientific, Inc.. All rights reserved. // Software License Agreement // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the // distribution. // // Neither the name of Sevun Scientific, Inc. nor the names of // its contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // //***************************************************************************** //***************************************************************************** // //! \addtogroup umsg_api //! @{ // //***************************************************************************** #include <stdbool.h> #include <stdint.h> #include "driverlib/sw_crc.h" #include "driverlib/uart.h" #include "inc/hw_memmap.h" #include "inc/hw_sysctl.h" #include "inc/hw_types.h" #include "inc/hw_uart.h" #include "umsg.h" //***************************************************************************** // //! Write U8 value to UART and update running CRC from message stream //! //! \return None. // //***************************************************************************** void UARTWriteU8(uint32_t ui32Base, const uint8_t writeData, uint16_t *runningCrc) { UARTCharPutNonBlocking(ui32Base, writeData); *runningCrc = Crc16(*runningCrc, &writeData, 1); return; } //***************************************************************************** // //! Write U16 value to UART and update running CRC from message stream //! //! \return None. // //***************************************************************************** void UARTWriteU16(uint32_t ui32Base, const uint16_t writeData, uint16_t *runningCrc) { UARTWriteU8(ui32Base, (uint8_t)(0xFF & (writeData >> 8)), runningCrc); UARTWriteU8(ui32Base, (uint8_t)(0xFF & writeData), runningCrc); return; } //***************************************************************************** // //! Read U8 value from UART and update running CRC from message stream //! //! \return U8 data. // //***************************************************************************** uint8_t UARTReadU8(uint32_t ui32Base, uint16_t *runningCrc) { uint8_t localReadData = UARTCharGetNonBlocking(ui32Base); *runningCrc = Crc16(*runningCrc, &localReadData, 1); return localReadData; } //***************************************************************************** // //! Read U16 value from UART and update running CRC from message stream //! //! \return U16 data. // //***************************************************************************** uint16_t UARTReadU16(uint32_t ui32Base, uint16_t *runningCrc) { uint16_t localReadData = (((uint16_t)(UARTReadU8(ui32Base, runningCrc)) << 8) & 0xFF00) | (((uint16_t)(UARTReadU8(ui32Base, runningCrc))) & 0xFF); return localReadData; } //***************************************************************************** // //! Configures a message object in the UMSG controller. //! //! \return None. // //***************************************************************************** void UARTMessageSet(uint32_t ui32Base, tUARTMsgObject *psMsgObject) { psMsgObject->ui32Flags = MSG_OBJ_NO_FLAGS; // dummy CRC value uint16_t tempCrc = 0; // initilize CRC value uint16_t ui16CRCcalc = 0; const uint16_t startWord = ((((uint16_t)UMSG_START_BYTE) << 8) & 0xFF00) | ((uint16_t)UMSG_START_BYTE); // start new message with 0xFFFF UARTWriteU16(ui32Base, startWord, &tempCrc); // send message id UARTWriteU16(ui32Base, psMsgObject->ui16MsgID, &ui16CRCcalc); // send data unsigned int uIdx; for(uIdx = 0; uIdx < psMsgObject->ui32MsgLen; uIdx++) { UARTWriteU8(ui32Base, psMsgObject->pui8MsgData[uIdx], &ui16CRCcalc); } // send CRC UARTWriteU16(ui32Base, ui16CRCcalc, &tempCrc); } //***************************************************************************** // //! Reads a UMSG message from one of the message object buffers. //! //! \return None. // //***************************************************************************** void UARTMessageGet(uint32_t ui32Base, tUARTMsgObject *psMsgObject) { psMsgObject->ui32Flags = MSG_OBJ_NO_FLAGS; // dummy CRC value uint16_t tempCrc = 0; // check if next byte could be start of 0xFFFF word if(UMSG_START_BYTE != UARTReadU8(ui32Base, &tempCrc)) { return; } // if so, check next byte and GO if it matches if(UMSG_START_BYTE == UARTReadU8(ui32Base, &tempCrc)) { // initilize CRC received value uint16_t ui16CRCrx = 0; // initilize CRC calculated value uint16_t ui16CRCcalc = 0; // read message ID psMsgObject->ui16MsgID = UARTReadU16(ui32Base, &ui16CRCcalc); // receive data unsigned int uIdx; for(uIdx = 0; uIdx < psMsgObject->ui32MsgLen; uIdx++) { psMsgObject->pui8MsgData[uIdx] = UARTReadU8(ui32Base, &ui16CRCcalc); } // read CRC... ui16CRCrx = UARTReadU16(ui32Base, &tempCrc); // ...then check for data integrity against calculated value if(ui16CRCrx == ui16CRCcalc) { psMsgObject->ui32Flags |= MSG_OBJ_NEW_DATA; } else { psMsgObject->ui32Flags |= MSG_OBJ_DATA_LOST; } } } //***************************************************************************** // // Close the Doxygen group. //! @} // //*****************************************************************************
Omicrxn/U.N.Squadron
PowerupOrange.h
<reponame>Omicrxn/U.N.Squadron<gh_stars>1-10 #ifndef __POWERUPORANGE_H__ #define __POWERUPORANGE_H__ #include "Weapon.h" #include "Path.h" class PowerupOrange : public Weapon { public: // Constructor (x y coordinates in the world) // Creates animation and movement data and the collider PowerupOrange(int x, int y); void Update() override; void OnCollision(Collider* collider) override; private: // A set of steps that define the position in the screen // And an animation for each step Path pathOrange; Animation animPowerOrange; }; #endif // __POWERUPORANGE_H__#pragma once#pragma once
Omicrxn/U.N.Squadron
StealthBomber.h
<filename>StealthBomber.h<gh_stars>1-10 #pragma once #ifndef _STEALTHBOMBER_H__ #define _STEALTHBOMBER_H__ #include "Enemy.h" #include "Path.h" enum SBState { SPAWNING, IDLE,SHOOTING }; class StealthBomber : public Enemy { public: StealthBomber(int x, int y, bool spawnRight); void Update() override; void OnCollision(Collider* collider) override; private: Path spawnPath; Path normalPath; Animation idle; Animation shooting; SDL_Rect rect; unsigned int shootingFrequency; unsigned int shootingFrequency2; bool damaged = false; int currentTime = 0; SBState state = SPAWNING; iPoint idlePosition = { 0, 0}; }; #endif // !_STEALTHBOMBER_H_
Omicrxn/U.N.Squadron
Globals.h
<filename>Globals.h #pragma once #ifndef __GLOBALS_H__ #define __GLOBALS_H__ #include <windows.h> #define LOG(format, ...) Log(__FILE__,__LINE__,format,__VA_ARGS__); void Log(const char file[], int line, const char* format, ...); #define EXIT_FAILURE 1 #define EXIT_SUCCESS 0 #define MIN( a, b ) ( ((a) < (b)) ? (a) : (b) ) #define MAX( a, b ) ( ((a) > (b)) ? (a) : (b) ) enum update_status { UPDATE_CONTINUE = 1, UPDATE_STOP, UPDATE_ERROR }; typedef unsigned char uchar; typedef unsigned int uint; // Settings #define WINDOW_ICON_PATH "Assets/Sprites/windowIcon.bmp" #define SCREEN_WIDTH 256 //ratio 8:7 #define SCREEN_HEIGHT 224 #define WIN_FULLSCREEN 0 #define WIN_FULLSCREEN_DESKTOP 0 #define SCREEN_SIZE 3 #define WIN_BORDERLESS 0 #define WIN_RESIZABLE 1 #define REN_VSYNC 1 #define WIN_TITLE "U.N. Squadron" #endif // __GLOBALS_H__
Omicrxn/U.N.Squadron
GreenFighterPlane.h
<reponame>Omicrxn/U.N.Squadron #pragma once #include "Enemy.h" #include "Path.h" enum GFState { gSPAWNING, gIDLE }; class GreenFighterPlane : public Enemy { public: // Constructor (x y coordinates in the world) // Creates animation and movement data and the collider GreenFighterPlane(int x, int y, bool spawnRight); // The enemy is going to follow different steps in the path // Position will be updated depending on the speed defined at each step void Update() override; void OnCollision(Collider* collider) override; private: Path spawnPathTop; Path spawnPathBot; Path idlePathTop; Path idlePathBot; Animation idle; Animation shooting; SDL_Rect rect; unsigned int shootingFrequency; GFState state = gSPAWNING; bool spawningTop = false; bool goingUp = false; iPoint idlePosition = { 0, 0 }; bool damaged = false; int currentTime = 0; };
Omicrxn/U.N.Squadron
ModulePlayer.h
<gh_stars>1-10 #pragma once #ifndef __MODULEPLAYER_H__ #define __MODULEPLAYER_H__ #include "Module.h" #include "p2Point.h" #include "SDL_rect.h" #include "Animation.h" struct SDL_Texture; class ModulePlayer : public Module { public: ModulePlayer(bool startEnabled); ~ModulePlayer(); bool Start(); bool Init(); update_status Update(); update_status PostUpdate(); bool CleanUp(); // The player's collider Collider* collider = nullptr; // Collision callback, called when the player intersects with another collider void OnCollision(Collider* c1, Collider* c2) override; // A flag to detect when the player has been destroyed bool destroyed = false; // Sound effects indices uint shootFx = 0; uint hitFx = 0; uint dieFx = 0; // Score uint score = 0; // Money uint money = 3000; // Total POW uint total = 0; // POW Level uint level = 1; bool maxAmmo = false; bool maxPow = false; iPoint GetPlayerPosition() { return position; } int GetCurrentFuel() { return currentFuel; } int GetMaxFuel() { return maxFuel; } int GetLifes() { return playerLifes; } // The whole list of weapons to know which one is the player selecting at each moment enum weapons { WEAPON_1, WEAPON_2, FALCON, WEAPON_4, SHELL, WEAPON_6, BOMB, WEAPON_8, CEILING, WEAPON_10, WEAPON_11, NONE }; // To know which is the current weapon (the last one that has been selected) uint currentWeapon; uint falconAmmo; uint shellAmmo; uint bombAmmo; uint ceilingAmmo; bool hasBeenHit; uint hasBeenHitCounter; private: iPoint position; SDL_Texture* texture = nullptr; Animation* current_anim = nullptr; Animation playerAnimRight; Animation playerAnimLeft; Animation playerSpinningRight; Animation playerSpinningLeft; SDL_Rect rectAnim; int maxFuel = 8, currentFuel = 8, playerLifes = 3; bool godMode = false; uint weaponCount; bool hasBought; bool damaged = false; int currentTime = 0; // Countdown to handle shot spacing int shotMaxCountdown = 13; int shotCountdown = 0; // Countdown to handle weapon shot spacing int weaponMaxCountdown = 20; int weaponCountdown = 0; // Countdown to handle weapon change spacing int changeMaxCountdown = 25; int changeCountdown = 0; // Ceiling countdown uint ceilingCountdown; uint collisionMaxCountdown = 30; uint collisionCountdown = 0; friend class ModuleLevel1; }; #endif // __MODULEPLAYER_H__
Omicrxn/U.N.Squadron
ModuleTextureManager.h
<reponame>Omicrxn/U.N.Squadron #pragma once #ifndef __ModuleTextures_H__ #define __ModuleTextures_H__ #include "Module.h" #include "Globals.h" #define MAX_TEXTURES 200 struct SDL_Texture; class ModuleTextureManager : public Module { public: ModuleTextureManager(bool startEnabled); ~ModuleTextureManager(); bool Init(); bool CleanUp(); SDL_Texture* const Load(const char* path); bool Unload(SDL_Texture* texture); void GetSize(const SDL_Texture* texture, uint& width, uint& height) const; inline uint GetTexturesCount() const { return texturesCount; }; SDL_Texture* textures[MAX_TEXTURES]; uint lastTexture = 0; private: // The amount of textures loaded into the array uint texturesCount = 0; }; #endif //__ModuleTextures_H__
Omicrxn/U.N.Squadron
ModuleStartScreen.h
#pragma once #ifndef __MODULESTARTSCREEN_H__ #define __MODULESTARTSCREEN_H__ #include "Module.h" #include "Animation.h" #include "p2Point.h" struct SDL_Texture; class ModuleStartScreen : public Module { public: ModuleStartScreen(bool startEnabled); ~ModuleStartScreen(); bool Start(); update_status Update(); update_status PostUpdate(); bool CleanUp(); // Sound effects indices uint chooseFx = 0; uint startFx = 0; private: SDL_Texture* tex = nullptr; SDL_Rect title; SDL_Rect text; Animation selector; Animation unicorn_anim; Animation* current_anim = nullptr; iPoint selectorPos; SDL_Rect rect; bool blink = false; }; #endif
Omicrxn/U.N.Squadron
SB_BombShrapnel.h
#pragma once #ifndef __SB_BOMBSHRAPNEL_H__ #define __SB_BOMBSHRAPNEL_H__ #include "Weapon.h" #include "Path.h" class SB_BombShrapnel : public Weapon { public: // Constructor (x y coordinates in the world) // Creates animation and movement data and the collider SB_BombShrapnel(int x, int y,unsigned int number); // The weapon is going to follow the different steps in the path // Position will be updated depending on the speed defined at each step void Update() override; private: // A set of steps that define the position in the screen // And an animation for each step //The paths start from the horizontal left and go clockwise // 2 // 1 3 // 0 4 // 7 5 // 6 // Path path0; Path path1; Path path2; Path path3; Path path4; Path path5; Path path6; Path path7; // This weapon has one sprite and one frame // We are keeping it an animation for consistency with other weapons Animation shrapnel0; Animation shrapnel1; Animation shrapnel2; Animation shrapnel3; Animation shrapnel4; Animation shrapnel5; Animation shrapnel6; Animation shrapnel7; unsigned int shrapnelNum = 0; }; #endif // !__SB_BOMBSHRAPNEL_H__
Omicrxn/U.N.Squadron
PowerupBlue.h
<gh_stars>1-10 #ifndef __POWERUPBLUE_H__ #define __POWERUPBLUE_H__ #include "Weapon.h" #include "Path.h" class PowerupBlue : public Weapon { public: // Constructor (x y coordinates in the world) // Creates animation and movement data and the collider PowerupBlue(int x, int y); void Update() override; void OnCollision(Collider* collider) override; private: // A set of steps that define the position in the screen // And an animation for each step Path pathBlue; Animation animPowerBlue; }; #endif // __POWERUPBLUE_H__#pragma once
Omicrxn/U.N.Squadron
Application.h
<reponame>Omicrxn/U.N.Squadron #pragma once #ifndef __APPLICATION_H__ #define __APPLICATION_H__ #include "Globals.h" class Module; class ModuleWindow; class ModuleInput; class ModuleTextureManager; class ModuleWinScreen; class ModuleAudio; class ModulePlayer; class ModuleLevel1; class ModuleLevel2; class ModuleParticles; class ModuleInitialScreen; class ModuleStartScreen; class ModuleLoseScreen; class ModuleFadeToBlack; class ModuleCollisions; class ModuleRenderer; class ModuleHUD; class ModuleEnemies; class ModuleFonts; class ModuleStore; class ModuleDebugInfo; class ModuleWeapons; class ModuleSelector; #define NUM_MODULES 22 class Application { public: // Constructor. Creates all necessary modules for the application Application(); ~Application(); Module* modules[NUM_MODULES]; ModuleWindow* window = nullptr; ModuleInput* input = nullptr; ModuleTextureManager* textures = nullptr; ModuleAudio* audio = nullptr; ModuleLevel1* lvl1 = nullptr; ModuleLevel2* lvl2 = nullptr; ModulePlayer* player = nullptr; ModuleInitialScreen* initialScreen = nullptr; ModuleStartScreen* startScreen = nullptr; ModuleLoseScreen* loseScreen = nullptr; ModuleWinScreen* winScreen = nullptr; ModuleParticles* particles = nullptr; ModuleCollisions* collisions = nullptr; ModuleFadeToBlack* transition = nullptr; ModuleHUD* HUD = nullptr; ModuleRenderer* render = nullptr; ModuleEnemies* enemies = nullptr; ModuleFonts* fonts = nullptr; ModuleStore* store = nullptr; ModuleDebugInfo* debugInfo = nullptr; ModuleWeapons* weapons = nullptr; ModuleSelector* selector = nullptr; // Initializes all modules bool Init(); // Updates all modules (PreUpdate, Update and PostUpdate) update_status Update(); // Releases all the application data bool CleanUp(); const int FPS = 60; const int frameDelay = 1000 / FPS; UINT32 frameStart = 0; int frameTime; }; // To make it global and be able to access from other calses without include extern Application* App; #endif // __APPLICATION_H__
Omicrxn/U.N.Squadron
ModuleSelector.h
#pragma once #ifndef __MODULESELECTOR_H__ #define __MODULESELECTOR_H__ #include "Module.h" #include "Globals.h" #include "Animation.h" #include "p2Point.h" enum selection { LEVEL1, LEVEL2 }; struct SDL_Texture; class ModuleSelector : public Module { public: ModuleSelector(bool startEnabled); ~ModuleSelector(); bool Start(); update_status Update(); update_status PostUpdate(); bool CleanUp(); // Id Fonts int greyFont = -1; bool GetSelected() { return selected; } bool selected = true; private: bool enterPressed = false; bool enterPressedTwice = false; SDL_Texture* tex1 = nullptr; SDL_Texture* tex2 = nullptr; SDL_Rect background; }; #endif
Omicrxn/U.N.Squadron
ModuleWindow.h
#pragma once #ifndef __ModuleWindow_H__ #define __ModuleWindow_H__ #include "Module.h" struct SDL_Window; struct SDL_Surface; class ModuleWindow : public Module { public: ModuleWindow(bool startEnabled); virtual ~ModuleWindow(); bool Init(); bool CleanUp(); SDL_Window* sdlWindow = nullptr; SDL_Surface* screenSurface = nullptr; SDL_Surface* windowIcon; }; #endif // __ModuleWindow_H__
Omicrxn/U.N.Squadron
ModuleLevel1.h
#pragma once #ifndef __MODULELEVEL1_H__ #define __MODULELEVEL1_H__ #include "Module.h" #include "Globals.h" #include "SDL_rect.h" #include "p2Point.h" struct SDL_Texture; class ModuleLevel1 : public Module { public: ModuleLevel1(bool startEnabled); ~ModuleLevel1(); bool Start(); update_status Update(); update_status PostUpdate(); bool CleanUp(); SDL_Texture* backgroundTexture = nullptr; SDL_Texture* backgroundTexture2 = nullptr; SDL_Rect sky; SDL_Rect mountains; SDL_Rect floor; unsigned int numSpawnedEnemies = 0; enum position { LEFTUP, LEFTDOWN, RIGHTUP, RIGHTDOWN }; enum direction { LEFTDIR, RIGHTDIR }; uint currentPosition; uint currentDirection; uint cameraSpeed = 7; uint proportion = 3; bool spinningRight; uint spinningRightCounter; bool spinningLeft; uint spinningLeftCounter; // Timer uint startTime; uint prevTime; uint currentTime; uint seconds; uint miliseconds; }; #endif
Omicrxn/U.N.Squadron
ModuleLoseScreen.h
<gh_stars>1-10 #pragma once #include "Module.h" #include "Globals.h" #include "SDL_timer.h" #include "SDL_rect.h" #include "Animation.h" struct SDL_Texture; class ModuleLoseScreen : public Module { public: ModuleLoseScreen(bool startEnabled); ~ModuleLoseScreen(); bool Start(); update_status Update(); update_status PostUpdate(); bool CleanUp(); uint loseFx = 0; private: SDL_Texture* tex = nullptr; Animation anim; Animation* current_anim = nullptr; // Id Fonts int greyFont = -1; int greenFont = -1; bool continue3; bool pressed = false; };
Omicrxn/U.N.Squadron
Weapon.h
<gh_stars>1-10 #ifndef __WEAPON_H__ #define __WEAPON_H__ #include "p2Point.h" #include "Animation.h" struct SDL_Texture; struct Collider; class Weapon { public: // Constructor // Saves the spawn position for later movement calculations Weapon(int x, int y); // Destructor virtual ~Weapon(); // Returns the weapon's collider const Collider* GetCollider() const; // Called from inhering weapon's Udpate // Updates animation and collider position virtual void Update(); // Called from ModuleWeapon's Update virtual void Draw(); // Collision response // Triggers an animation and a sound fx virtual void OnCollision(Collider* collider); // Sets flag for deletion and for the collider aswell virtual void SetToDelete(); public: // The current position in the world iPoint position; // The weapon's texture SDL_Texture* texture = nullptr; // Sound fx when destroyed int destroyedFx = 0; // A flag for the weapon removal. Important! We do not delete objects instantly bool pendingToDelete = false; protected: // A ptr to the current animation Animation* currentAnim = nullptr; // The weapon's collider Collider* collider = nullptr; // Original spawn position. Stored for movement calculations iPoint spawnPos; }; #endif // __WEAPON_H__
Omicrxn/U.N.Squadron
ModuleInput.h
#pragma once #ifndef __ModuleInput_H__ #define __ModuleInput_H__ #include "Module.h" #include "Globals.h" #include "SDL_scancode.h" #include "SDL.h" #define MAX_KEYS 300 #define MAX_PADS 4 struct _SDL_GameController; struct _SDL_Haptic; enum key_state { KEY_IDLE = 0, KEY_DOWN, KEY_REPEAT, KEY_UP }; struct GamePad { //Input data bool start, back, guide; bool x, y, a, b, l1, r1, l3, r3; bool up, down, left, right; float l2, r2; float l_x, l_y, r_x, r_y, l_dz, r_dz; //Controller data bool enabled; int index; _SDL_GameController* controller; _SDL_Haptic* haptic; //Rumble controller int rumble_countdown; float rumble_strength; }; class ModuleInput : public Module { public: ModuleInput(bool startEnabled); ~ModuleInput(); bool Init(); update_status PreUpdate(); bool CleanUp(); // Activates SDL device funcionallity when a gamepad has been connected void HandleDeviceConnection(int index); // Deactivates SDL device funcionallity when a gamepad has been disconnected void HandleDeviceRemoval(int index); // Called at PreUpdate // Iterates through all active gamepads and update all input data void UpdateGamepadsInput(); bool ShakeController(int id, int duration, float strength = 0.5f); const char* GetControllerName(int id) const; key_state keyboard[MAX_KEYS]; // An array to fill in all detected gamepads GamePad pads[MAX_PADS]; private: bool maximized = false; }; #endif // __ModuleInput_H__
Omicrxn/U.N.Squadron
ModuleStore.h
#pragma once #ifndef __MODULESTORE_H__ #define __MODULESTORE_H__ #include "Module.h" #include "Animation.h" #include "p2Point.h" struct SDL_Texture; class ModuleStore : public Module { public: ModuleStore(bool startEnabled); ~ModuleStore(); bool Start(); update_status Update(); update_status PostUpdate(); bool CleanUp(); char moneyText[10] = { "\0" }; // Sound effects indices uint chooseFx = 0; uint boughtFx = 0; uint noMoneyFx = 0; // Bit field to store all the weapons selected to start the game // The last 11 bits represent each weapon selectable for the player (from left to right) // For instance, 00000000 00000000 00000000 00000001 means that WEAPON_11 has been selected // With that we'll be able to know which weapons have been selected by the player without wasting memory unnecessarily :) uint weaponSelection = 0; // 00000000 00000000 00000000 00000000 private: SDL_Texture* tex = nullptr; SDL_Texture* tex2 = nullptr; SDL_Texture* tex3 = nullptr; SDL_Texture* tex4 = nullptr; SDL_Rect title; SDL_Rect text; SDL_Rect selector; SDL_Rect background; SDL_Rect alreadySelected; Animation talkStore; Animation unicorn_anim; Animation* current_anim = nullptr; iPoint selectorPos; // Id Fonts int greyFont = -1; int greenFont = -1; bool exitPressed = false; // Countdown to handle selector spacing int MaxCountdownR = 15; int CountdownR = 0; int MaxCountdownL = 15; int CountdownL = 0; // A few variables to manage the correct functioning of the store... // Not necessary for the remaining modules (because of that they are not defined in the .h) enum weapons { WEAPON_1, WEAPON_2, FALCON, WEAPON_4, SHELL, WEAPON_6, BOMB, WEAPON_8, CEILING, WEAPON_10, WEAPON_11, EXIT }; uint weapons[2][6] = { {WEAPON_1, WEAPON_2, FALCON, WEAPON_4, SHELL, WEAPON_6}, {BOMB, WEAPON_8, CEILING, WEAPON_10, WEAPON_11, EXIT} }; uint rows = 0; uint columns = 0; uint weapon = weapons[rows][columns]; /////////////////////////////////////////////////////////////////////////////////////////// enum storeState { FALCONSELECT, SHELLSELECT, BOMBSELECT, CEILINGSELECT, CANTHANDLE, BOUGHT, ALREADYBOUGHT, NOMONEY, EXITSELECT, BYE, IDLE }; storeState currentState = CANTHANDLE; uint storeStateCounter = 0; }; #endif // __MODULESTORE_H__
Omicrxn/U.N.Squadron
ModuleInitialScreen.h
#pragma once #ifndef __MODULEINITIALSCREEN_H__ #define __MODULEINITIALSCREEN_H__ #include "Module.h" #include "Globals.h" #include "SDL_timer.h" #include "SDL_rect.h" struct SDL_Texture; class ModuleInitialScreen : public Module { public: ModuleInitialScreen(bool startEnabled); ~ModuleInitialScreen(); bool Start(); update_status Update(); update_status PostUpdate(); bool CleanUp(); private: SDL_Texture* logoTex = nullptr; SDL_Texture* tex = nullptr; SDL_Rect logo; SDL_Rect screen; Uint32 startTime = 0; Uint32 endTime = 0; Uint32 actualTime = 0; }; #endif
Omicrxn/U.N.Squadron
Module.h
#pragma once #ifndef __MODULE_H__ #define __MODULE_H__ #include "Globals.h" struct Collider; class Module { private: bool enabled = true; public: Module(bool startEnabled); //Called at the beginning of the application execution virtual bool Init(); //Called when the module is activated virtual bool Start(); //Called at the beginning of each application loop virtual update_status PreUpdate(); //Called at the middle of each application loop virtual update_status Update(); //Called at the end of each application loop virtual update_status PostUpdate(); //Called at the end of the application virtual bool CleanUp(); //Called when two colliders are intersecting //and the module is registered as the listener virtual void OnCollision(Collider* c1, Collider* c2); // Switches isEnabled and calls Start() method void Enable(); // Switches isEnabled and calls CleanUp() method void Disable(); inline bool IsEnabled() const { return enabled; } public: const char* name = "None"; // Resources info uint activeFonts = 0; uint totalFonts = 0; uint activeTextures = 0; uint totalTextures = 0; uint activeColliders = 0; uint totalColliders = 0; uint activeFx = 0; uint totalFx = 0; }; #endif // __MODULE_H__
Omicrxn/U.N.Squadron
Bomb.h
<gh_stars>1-10 #ifndef __BOMB_H__ #define __BOMB_H__ #include "Weapon.h" #include "Path.h" class Bomb : public Weapon { public: // Constructor (x y coordinates in the world) // Creates animation and movement data and the collider Bomb(int x, int y); // The weapon is going to follow the different steps in the path // Position will be updated depending on the speed defined at each step void Update() override; void OnCollision(Collider* collider) override; private: // A set of steps that define the position in the screen // And an animation for each step Path path; // This weapon has one sprite and one frame // We are keeping it an animation for consistency with other weapons Animation dropRight1; Animation dropRight2; Animation dropLeft1; Animation dropLeft2; }; #endif // __BOMB_H__
Omicrxn/U.N.Squadron
p2Point.h
#pragma once #ifndef __PointOperations_h__ #define __PointOperations_h__ #include "Globals.h" #include <math.h> template<class TYPE> class PointOperations { public: TYPE x, y; PointOperations() {} PointOperations(const PointOperations& v) { this->x = v.x; this->y = v.y; } PointOperations(const TYPE& x, const TYPE& y) { this->x = x; this->y = y; } PointOperations& create(const TYPE& x, const TYPE& y) { this->x = x; this->y = y; return(*this); } // Math ------------------------------------------------ PointOperations operator -(const PointOperations& v) const { PointOperations r; r.x = x - v.x; r.y = y - v.y; return(r); } PointOperations operator + (const PointOperations& v) const { PointOperations r; r.x = x + v.x; r.y = y + v.y; return(r); } const PointOperations& operator -=(const PointOperations& v) { x -= v.x; y -= v.y; return(*this); } const PointOperations& operator +=(const PointOperations& v) { x += v.x; y += v.y; return(*this); } bool operator ==(const PointOperations& v) const { return (x == v.x && y == v.y); } bool operator !=(const PointOperations& v) const { return (x != v.x || y != v.y); } // Utils ------------------------------------------------ bool IsZero() const { return (x == 0 && y == 0); } PointOperations& SetToZero() { x = y = 0; return(*this); } PointOperations& Negate() { x = -x; y = -y; return(*this); } // Distances --------------------------------------------- TYPE DistanceTo(const PointOperations& v) const { TYPE fx = x - v.x; TYPE fy = y - v.y; return (TYPE)sqrtf(float(fx * fx) + float(fy * fy)); } TYPE DistanceNoSqrt(const PointOperations& v) const { TYPE fx = x - v.x; TYPE fy = y - v.y; return (fx * fx) + (fy * fy); } TYPE DistanceManhattan(const PointOperations& v) const { return abs(v.x - x) + abs(v.y - y); } }; typedef PointOperations<int> iPoint; typedef PointOperations<float> fPoint; #endif // __PointOperations_h__
Omicrxn/U.N.Squadron
SB_Bomb.h
<reponame>Omicrxn/U.N.Squadron<gh_stars>1-10 #pragma once #ifndef __SB_BOMB_H__ #define __SB_BOMB_H__ #include "Weapon.h" #include "Path.h" class SB_Bomb : public Weapon { public: // Constructor (x y coordinates in the world) // Creates animation and movement data and the collider SB_Bomb(int x, int y,unsigned int number); // The weapon is going to follow the different steps in the path // Position will be updated depending on the speed defined at each step void Update() override; void Explosion(Path* path); private: unsigned int bombNum; // A set of steps that define the position in the screen // And an animation for each step Path path0; Path path1; // This weapon has one sprite and one frame // We are keeping it an animation for consistency with other weapons Animation bomb; }; #endif // !__SB_BOMB_H__
Omicrxn/U.N.Squadron
ModuleLevel2.h
<reponame>Omicrxn/U.N.Squadron<gh_stars>1-10 #pragma once #ifndef __MODULELEVEL2_H__ #define __MODULELEVEL2_H__ #include "Module.h" #include "Globals.h" #include "SDL_rect.h" #include "p2Point.h" struct SDL_Texture; class ModuleLevel2 : public Module { public: ModuleLevel2(bool startEnabled); ~ModuleLevel2(); bool Start(); update_status Update(); update_status PostUpdate(); bool CleanUp(); void InfiniteScrolling(fPoint* top, fPoint* top2, fPoint* bot, fPoint* bot2, SDL_Rect* topLayer, SDL_Rect* botLayer, float speed); SDL_Texture* backgroundTexture = nullptr; SDL_Rect centerLayer; SDL_Rect firstTopLayer; SDL_Rect secondTopLayer; SDL_Rect thirdTopLayer; SDL_Rect firstBottomLayer; SDL_Rect secondBottomLayer; SDL_Rect thirdBottomLayer; fPoint centerPos,firstTopPos,secondTopPos,thirdTopPos,firstBotPos, secondBotPos, thirdBotPos; fPoint centerPos2,firstTopPos2,secondTopPos2,thirdTopPos2,firstBotPos2, secondBotPos2, thirdBotPos2; float centerSpeed, firstSpeed, secondSpeed, thirdSpeed; unsigned int numSpawnedEnemies = 0; bool bossDead = false; }; #endif
Omicrxn/U.N.Squadron
ModuleWeapons.h
<gh_stars>1-10 #ifndef __MODULE_WEAPONS_H__ #define __MODULE_WEAPONS_H__ #include "Module.h" #define MAX_WEAPONS 100 // Create new weapon types: enum class WEAPON_TYPE { NO_TYPE, BOMB, SHELL, FALCON, CEILING, GF_HOOK, SB_BOMB, SB_SHRAPNEL, POWERUP_BLUE, POWERUP_ORANGE, LEVEL1GUN }; struct WeaponSpawnpoint { WEAPON_TYPE type = WEAPON_TYPE::NO_TYPE; int x, y; }; class Weapon; struct SDL_Texture; class ModuleWeapons : public Module { public: // Constructor ModuleWeapons(bool startEnabled); // Destructor ~ModuleWeapons(); // Called when the module is activated // Loads the necessary textures for the weapons bool Start() override; // Called at the beginning of the application loop // Removes all weapons pending to delete update_status PreUpdate() override; // Called at the middle of the application loop // Handles all weapons logic and spawning/despawning update_status Update() override; // Called at the end of the application loop // Iterates all the weapons and draws them update_status PostUpdate() override; // Called on application exit // Destroys all active weapons left in the array bool CleanUp() override; // Called when an weapon collider hits another collider // The weapon is destroyed and an explosion particle is fired void OnCollision(Collider* c1, Collider* c2) override; // Spawns a new weapon using the data from the queue void SpawnWeapon(WEAPON_TYPE weaponType,int x=0, int y=0); // Destroys any weapons that have moved outside the camera limits void DespawnWeapon(); void SpawnWeapon(WEAPON_TYPE weaponType,int x, int y, unsigned int number); private: // All spawned weapons in the scene Weapon* weapons[MAX_WEAPONS] = { nullptr }; // The weapons sprite sheet SDL_Texture* texture = nullptr; // The audio fx for destroying an weapon int weaponDestroyedFx = 0; }; #endif // __MODULE_WEAPONS_H__
Omicrxn/U.N.Squadron
ModuleWinScreen.h
<filename>ModuleWinScreen.h #pragma once #ifndef __MODULEWINSCREEN_H__ #define __MODULEWINSCREEN_H__ #include "Module.h" #include "Globals.h" #include "SDL_timer.h" #include "SDL_rect.h" struct SDL_Texture; class ModuleWinScreen : public Module { public: ModuleWinScreen(bool startEnabled); ~ModuleWinScreen(); bool Start(); update_status Update(); update_status PostUpdate(); bool CleanUp(); private: SDL_Texture* tex = nullptr; SDL_Rect screen; Uint32 startTime; Uint32 endTime; Uint32 actualTime; }; #endif
Omicrxn/U.N.Squadron
ModuleParticles.h
#pragma once #ifndef __MODULEPARTICLES_H__ #define __MODULEPARTICLES_H__ #include "Application.h" #include "Animation.h" #include "p2Point.h" #include "Module.h" #include "SDL.h" #include "ModuleCollisions.h" #define MAX_ACTIVE_PARTICLES 200 struct SDL_Texture; struct Collider; struct Particle { public: // Constructor Particle(); // Copy constructor Particle(const Particle& p); ~Particle(); // Called in ModuleParticles' Update // Handles the logic of the particle // Returns false when the particle reaches its lifetime bool Update(); public: // Defines the position in the screen iPoint position; // Defines the speed at which the particle will move (pixels per second) iPoint speed; // A set of rectangle sprites Animation anim; // Defines wether the particle is alive or not // Particles will be set to not alive until "spawnTime" is reached bool isAlive = false; // Defines the time when the particle will be spawned int frameCount = 0; // Defines the total amount of time during which the particle will be active (in miliseconds) Uint32 lifetime = 0; // The particle's collider Collider* collider = nullptr; bool isWeapon = false; }; class ModuleParticles : public Module { public: // Constructor // Initializes all the particles in the array to nullptr ModuleParticles(bool startEnabled); //Destructor ~ModuleParticles(); // Called when the module is activated // Loads the necessary textures for the particles bool Start() override; // Called at the middle of the application loop // Iterates all the particles and calls its Update() // Removes any "dead" particles update_status Update() override; // Called at the end of the application loop // Iterates all the particles and draws them update_status PostUpdate() override; // Called on application exit // Destroys all active particles left in the array bool CleanUp() override; // Called when a particle collider hits another collider void OnCollision(Collider* c1, Collider* c2) override; // Creates a new particle and adds it to the array // Param particle - A template particle from which the new particle will be created // Param x, y - Position x,y in the screen (upper left axis) // Param delay - Delay time from the moment the function is called until the particle is displayed in screen void AddParticle(const Particle& particle, int x, int y, Collider::Type colliderType = Collider::Type::NONE, uint delay = 0); inline uint GetParticlesCount() const { return particlesCount; }; private: // Particles spritesheet loaded into an SDL Texture SDL_Texture* particlesTexture = nullptr; // An array to store and handle all the particles Particle* particles[MAX_ACTIVE_PARTICLES] = { nullptr }; // An index to the last added particle uint lastParticle = 0; // Total amount of particles loaded into the array uint particlesCount = 0; // Weapons particles spritesheet loaded into an SDL Texture SDL_Texture* weaponsParticlesTexture = nullptr; public: // Template particle for an explosion Particle explosion; Particle enemyExplosion; Particle bullet1; Particle bullet2; Particle bullet3; Particle bullet4; Particle bullet5; Particle enemyBullet; Particle turretMissile; Particle greenFighterBullet; Particle sbFirecannon; Particle sbExplosion; Particle sbSparks; Particle sbBombs; Particle sbBombExplosion; Particle falconExplosion; Particle shellExplosion; Particle bombExplosion; Particle ceilingExplosion; }; #endif
Omicrxn/U.N.Squadron
SetBulletDirection.h
<filename>SetBulletDirection.h #include "Enemy.h" void SetBulletDirection(Enemy* enemy);
Omicrxn/U.N.Squadron
ModuleRenderer.h
#pragma once #ifndef __ModuleRenderer_H__ #define __ModuleRenderer_H__ #include "Module.h" #include "SDL_rect.h" struct SDL_Texture; struct SDL_Renderer; class ModuleRenderer : public Module { public: ModuleRenderer(bool startEnabled); ~ModuleRenderer(); bool Init(); update_status PreUpdate(); update_status Update(); update_status PostUpdate(); bool CleanUp(); bool Blit(SDL_Texture* texture, int x, int y, const SDL_Rect* section = nullptr, float speed = 1.0f, bool useCamera = true,bool initial = false); bool DrawQuad(const SDL_Rect& rect, Uint8 r, Uint8 g, Uint8 b, Uint8 a, float speed = 1.0f); SDL_Renderer* renderer = nullptr; SDL_Rect camera; }; #endif //__ModuleRenderer_H__
naudhizb/NumOperation
NumOperation.h
<gh_stars>0 /** * @file NumOperation.h * @author naudhizb (<EMAIL>) * @brief * @version 0.1 * @date 2021-01-27 * * @copyright Copyright (c) 2021 * */ #ifndef NUMOPERATION_H_ #define NUMOPERATION_H_ #if __cplusplus extern "C" { #endif #include <stdint.h> #define NumOp_Saturate(data, min, max) ((data) < (min))?(min):((max) < (data))?(max):(data) float NumOp_GetPercentage(float data, float min, float max); float NumOp_MapValue(float input, float input_min, float input_max, float map_min, float map_max); int32_t NumOp_GetDiff(uint32_t curr, uint32_t prev, uint32_t max); #if __cplusplus } #endif #endif /* NUMOPERATION_H_ */
naudhizb/NumOperation
NumOperation.c
/** * @file NumOperation.c * @author naudhizb (<EMAIL>) * @brief * @version 0.1 * @date 2021-01-29 * * @copyright Copyright (c) 2021 * */ #include "NumOperation.h" #include <stdio.h> float NumOp_GetPercentage(float data, float min, float max){ float percent = (data - min) / (max - min); return percent; } float NumOp_MapValue(float input, float input_min, float input_max, float map_min, float map_max){ float percent = NumOp_GetPercentage(input, input_min, input_max); float diff = (map_max - map_min); float output = (diff * percent) + map_min; return output; } /** * @brief Get Rotary Encoder differential. * curr, prev value must be in [0 max) * * @param curr current encoder counter * @param prev previous encodeer counter * @param max maximum encoder counter value curr < max, prev < max. up to 0x3FFFFFFF * @return int32_t differential value [-max/2 max/2] */ int32_t NumOp_GetDiff(uint32_t curr, uint32_t prev, uint32_t max){ int32_t diff = 0; const uint32_t half_max = max/2; diff = (int32_t)curr - (int32_t)prev; diff += half_max; if(diff < 0){ diff += max; } diff %= max; diff -= half_max; return diff; } int32_t NumOp_GetDiffTest(uint32_t curr, uint32_t prev, uint32_t max, int32_t diff_expect){ int32_t diff_result; printf("Start:[%d]:[%d] @ %lu %lu max: 0x%08X\n", diff_expect, diff_result, curr, prev, max); for(uint32_t i = 0; i < max; i++){ uint32_t curr_i = (curr+i)%(max); uint32_t prev_i = (prev+i)%(max); diff_result = NumOp_GetDiff(curr_i, prev_i, max); if(diff_result != diff_expect){ printf("diff:(index:%lu)[%d]:[%d] @ curr_i:%lu prev_i:%lu\n\n", i, diff_expect, diff_result, curr_i, prev_i); return 1; } else { // printf("diff:(index:%lu)[%d]:[%d] @ curr_i:%lu prev_i:%lu\n", i, diff_expect, diff_result, curr_i, prev_i); } if(i == max){ printf("Max reached. break\n"); break; } } printf("final:[%d]:[%d] @ %lu %lu max: 0x%08X\n\n", diff_expect, diff_result, curr, prev, max); return 0; } int main(void){ printf("Hello world!\n"); const uint32_t max = UINT32_MAX & (~0xC0000000); // NumOp_GetDiff(0, 255, max); // error case NumOp_GetDiffTest(1, 0, max, 1); NumOp_GetDiffTest(0, 1, max, -1); NumOp_GetDiffTest(2, 0, max, 2); NumOp_GetDiffTest(0, 2, max, -2); NumOp_GetDiffTest(0, max/2-1, max, -(max/2-1)); NumOp_GetDiffTest((max/2-1), 0, max, (max/2-1)); return 0; }
CMTFrostyy/GTA127_PS4505-Native_Caller
gtaPayload/include/invoker.h
#pragma once #include "types.h" #include <utility> // struct Native_s { // struct Native_s *lastNativeTable; // u64 nativeFunctions[7]; // u64 nativeCount; // u64 nativeHashes[7]; // }; struct NativeArg_s { u64* returnValue; u32 argCount; u8 padding1[4]; u64* argValues; u32 vectorCount; u8 padding2[4]; Vector3* argVectors[4]; Vector4 tempVectors[4]; }; extern NativeArg_s nativeArg; void callHash(u64 hash); void resetArgs(); void setVectors(); template<typename T> inline void pushArg(T value) { *(T*)&nativeArg.argValues[nativeArg.argCount] = value; nativeArg.argCount++; } template<typename R> inline R getReturn() { return *(R*)&nativeArg.returnValue[0]; } template<typename N, typename... A> N invoke(u64 hash, A &&... args) { resetArgs(); int dummy[] = { 0, ((void)pushArg(std::forward<A>(args)), 0) ... }; callHash(hash); setVectors(); return getReturn<N>(); }
CMTFrostyy/GTA127_PS4505-Native_Caller
source/main.c
#include "ps4.h" #include "kern.h" #include "proc.h" #include "gta.h" extern char gtaPayload[]; extern int gtaPayloadSize; int gamePID; void* hookAddress; double(*ceil)(double x); int(*sceSysUtilSendSystemNotificationWithText)(int messageType, char* message); void sysNotify(char* msg) { sceSysUtilSendSystemNotificationWithText(222, msg); } BOOL regionCheck() { procAttach(gamePID); u64 gameCheck; procReadBytes(gamePID, RegionCheckAddress, (void*)&gameCheck, sizeof(gameCheck)); if (gameCheck == RegionBytes) { sysNotify("GTA V detected."); hookAddress = HookAddress; } else { sysNotify("Failed to detect GTA V."); procDetach(gamePID); return FALSE; } procDetach(gamePID); return TRUE; } BOOL setupDone() { procAttach(gamePID); BOOL allocationNeeded; procReadBytes(gamePID, &gtaVars->allocationNeeded, &allocationNeeded, sizeof(allocationNeeded)); procDetach(gamePID); return !allocationNeeded; } void runSetup() { procAttach(gamePID); BOOL allocationNeeded = TRUE; procWriteBytes(gamePID, &gtaVars->allocationNeeded, &allocationNeeded, sizeof(allocationNeeded)); void* null = NULL; procWriteBytes(gamePID, &gtaVars->executableSpace, &null, sizeof(null)); procWriteBytes(gamePID, &gtaVars->dataSpace, &null, sizeof(null)); int executableSize = (int)ceil((double)gtaPayloadSize / 0x4000) * 0x4000; procWriteBytes(gamePID, &gtaVars->allocationSize, &executableSize, sizeof(executableSize)); procWriteBytes(gamePID, PayloadAddress, nativeHook, 0x1000); u8 syscallASM[] = { SyscallBytes }; procWriteBytes(gamePID, SyscallAddress, syscallASM, sizeof(syscallASM)); u8 hookASM[] = { HookBytes }; procWriteBytes(gamePID, hookAddress, hookASM, sizeof(hookASM)); procDetach(gamePID); } void startExecution() { procAttach(gamePID); void* executableSpace; procReadBytes(gamePID, &gtaVars->executableSpace, &executableSpace, sizeof(executableSpace)); procWriteBytes(gamePID, executableSpace, gtaPayload, gtaPayloadSize); procDetach(gamePID); } int _main(void) { initKernel(); initLibc(); kexec(kernelPayload, NULL); int libc = sceKernelLoadStartModule("libSceLibcInternal.sprx", 0, NULL, 0, 0, 0); RESOLVE(libc, ceil); int sysUtil = sceKernelLoadStartModule("/system/common/lib/libSceSysUtil.sprx", 0, NULL, 0, 0, 0); RESOLVE(sysUtil, sceSysUtilSendSystemNotificationWithText); sysNotify("Payload loaded.\nPlease launch GTA V."); gamePID = findProcess("eboot.bin"); sceKernelSleep(3); if (!regionCheck()) { return 0; } sysNotify("Setting up environment."); runSetup(); while (!setupDone()) sceKernelSleep(3); startExecution(); sysNotify("Mods activated.\nCredits to EROOTIIK!"); return 0; }
scveloso/Software
src/software/ai/intent/intent.h
#pragma once #include <string> #include <vector> #include "software/ai/intent/avoid_area.h" // We forward-declare the IntentVisitor interface (pure virtual class) because we need // to know about the existence of this class in order to accept visitors with the // accept() function. We cannot use an #include statement because this creates a cyclic // dependency // // This class can be found in ai/intent/intent_visitor.h class IntentVisitor; /** * An intent is a simple "thing" a robot or player may want to do. It specifies WHAT a * robot should do, not necessarily exactly how it will do it. Examples are shooting at * a point (for example the enemy net), or moving to a location. * * Intents can be considered to be one level above Primitives in terms of abstraction. * Primitives are simply the smallest/simplest action a robot can take and are not * concerned with gameplay logic, while Intents do deal with gameplay logic. * * We define an Abstract base class for Intents, despite not providing very many * pure-virtual functions, so that we can create generic structures of Intents. * For example we can create vectors of generic Intent objects (using pointers) * which is easier than a separate container for each type of Intent. */ class Intent { public: /** * Creates a new Intent with the given priority. A larger number indicates a higher * priority. The priority value must be in the range [0, 100] * * @param priority The priority of this Intent */ explicit Intent(unsigned int priority); /** * Returns the name of this Intent * * @return the name of this Intent */ virtual std::string getIntentName(void) const = 0; /** * Returns the priority of this Intent. The priority value is an integer in the range * [0, 100] that indicates the priority of this Intent. * * @return the priority of this Intent */ unsigned int getPriority(void) const; /** * Sets the priority of this Intent. The priority value must be an integer in the * range [0, 100] */ void setPriority(unsigned int new_priority); /** * Compares Intents for equality. Intents are considered equal if all * their member variables are equal. * * @param other the Intents to compare with for equality * @return true if the Intents are equal and false otherwise */ bool operator==(const Intent& other) const; /** * Compares Intents for inequality. * * @param other the Intent to compare with for inequality * @return true if the Intents are not equal and false otherwise */ bool operator!=(const Intent& other) const; /** * Accepts an Intent Visitor and calls the visit function * * @param visitor An Intent Visitor */ virtual void accept(IntentVisitor& visitor) const = 0; /** * Get the areas this intent should avoid moving into * * @return The areas this intent should avoid moving into */ std::vector<AvoidArea> getAreasToAvoid() const; /** * Set the areas this intent should avoid moving into * * @param areas_to_avoid The areas this intent should avoid moving into */ void setAreasToAvoid(const std::vector<AvoidArea>& areas_to_avoid); virtual ~Intent() = default; private: /** * The priority of this intent. Must be in the range [0, 100] * higher value => higher priority */ unsigned int priority; /** * The areas this intent should avoid moving into. These are enforced by * the navigator */ std::vector<AvoidArea> areas_to_avoid; };
scveloso/Software
src/software/ai/world/robot_capabilities.h
#pragma once #include <bitset> #include <initializer_list> #include <ostream> class RobotCapabilityFlags { public: typedef enum { Kick = 0, Chip = 1, Dribble = 2, MAX = 3 } RobotCapability; /** * returns a RobotCapabilityFlags object with all of the capabilities * @return RobotCapabilityFlags with all capabilities set */ static RobotCapabilityFlags allCapabilities(); /** * Construct a new RobotCapabilities with the specified capabilities * @param capabilities a list of capabilities */ RobotCapabilityFlags(const std::initializer_list<RobotCapability>& capabilities); /** * Returns true if the RobotCapabilityFlags has the specified capability, otherwise * false * @param capability a capability * @return true if the RobotCapabilityFlags has the specified capability */ bool hasCapability(const RobotCapability& capability) const; /** * Returns true if the current RobotCapabilityFlags has at least the capabilities of * the other RobotCapabilityFlags * @param other another RobotCapabilityFlags * @return true if this has at least the capabilities in the other * RobotCapabilityFlags */ bool hasAllCapabilities(const RobotCapabilityFlags& other) const; /** * True if the other RobotCapabilityFlags has exactly the same capabilities as this * one * @param other another RobotCapabilityFlags * @return True if the other RobotCapabilityFlags has exactly the same capabilities as * this one */ bool operator==(const RobotCapabilityFlags& other) const; /** * adds a capability to this RobotCapabilityFlags * @param capability a capability */ void addCapability(const RobotCapability& capability); /** * Removes a capability from this RobotCapabilityFlags * @param capability a capability */ void removeCapability(const RobotCapability& capability); private: std::bitset<MAX> capability_bits; }; inline RobotCapabilityFlags RobotCapabilityFlags::allCapabilities() { return RobotCapabilityFlags{RobotCapabilityFlags::Kick, RobotCapabilityFlags::Chip, RobotCapabilityFlags::Dribble}; } inline RobotCapabilityFlags::RobotCapabilityFlags( const std::initializer_list<RobotCapability>& _capabilities) { for (const RobotCapability& cap : _capabilities) { capability_bits.set(cap); } } inline bool RobotCapabilityFlags::hasCapability(const RobotCapability& capability) const { return capability_bits.test(capability); } inline bool RobotCapabilityFlags::operator==(const RobotCapabilityFlags& other) const { return capability_bits == other.capability_bits; } inline void RobotCapabilityFlags::addCapability( const RobotCapabilityFlags::RobotCapability& capability) { capability_bits.set(capability, true); } inline void RobotCapabilityFlags::removeCapability( const RobotCapabilityFlags::RobotCapability& capability) { capability_bits.set(capability, false); } inline bool RobotCapabilityFlags::hasAllCapabilities( const RobotCapabilityFlags& other) const { return (capability_bits & other.capability_bits) == other.capability_bits; } inline std::ostream& operator<<(std::ostream& os, const RobotCapabilityFlags& capabilityFlags) { os << "{"; if (capabilityFlags.hasCapability(RobotCapabilityFlags::Dribble)) { os << "Dribble, "; } if (capabilityFlags.hasCapability(RobotCapabilityFlags::Kick)) { os << "Kick, "; } if (capabilityFlags.hasCapability(RobotCapabilityFlags::Chip)) { os << "Chip"; } os << "}"; return os; }
scveloso/Software
src/software/ai/hl/stp/tactic/crease_defender_tactic.h
<filename>src/software/ai/hl/stp/tactic/crease_defender_tactic.h #pragma once #include "software/ai/hl/stp/evaluation/enemy_threat.h" #include "software/ai/hl/stp/tactic/tactic.h" #include "software/geom/segment.h" /** * A crease defender moves around the exterior of our defense box to help shadow * shots against the enemy * * XX <-- Enemy * XX * O <-- Ball * * * * ++ ++ <--- Two crease defenders * ++ ++ * * +--------------------+ * | | * | | * | ++ <-- Goalie *+----------------------+---------++---------+------------------+ */ class CreaseDefenderTactic : public Tactic { public: enum LeftOrRight { LEFT, RIGHT }; /** * Creates a new CreaseDefenderTactic */ explicit CreaseDefenderTactic(const Field &field, const Ball &ball, const Team &friendly_team, const Team &enemy_team, LeftOrRight left_or_right); std::string getName() const override; /** * Updates the parameters for this CreaseDefenderTactic. * // TODO: comment */ void updateParams(const Ball &ball, const Field &field, const Team &friendly_team, const Team &enemy_team); /** * Calculates the cost of assigning the given robot to this Tactic. Prefers robots * closer to the destination * * @return A cost in the range [0,1] indicating the cost of assigning the given robot * to this tactic. Lower cost values indicate a more preferred robot. */ double calculateRobotCost(const Robot &robot, const World &world) override; private: void calculateNextIntent(IntentCoroutine::push_type &yield) override; /** * Calculate the position and orientation we would like the defender to be in * * @return The position and orientation we would like the defender to be in, or * std::nullopt if we could not compute one */ std::optional<std::pair<Point, Angle>> calculateDesiredState(const Robot &robot); /** * Gets the segments that make up the path the Crease Defender should follow * @param field * @return The segments that make up the path the Crease Defender should follow */ static std::vector<Segment> getPathSegments(Field field); /** * Gets a point on the defender crease path where a ray from the goalie at the given * angle will intersect * * @param field The field the path is onAngle angle * @param goalie The goalie the defenders are working with * @param ball The ball * @param offset The angle to offset ray formed from the goalie to the ball by * * @return The point on the path the ray from the goalie intersects, if */ static std::optional<Point> getPointOnCreasePath(Field field, Robot goalie, Ball ball, Angle offset); // Tactic parameters Ball ball; Field field; Team friendly_team; Team enemy_team; LeftOrRight left_or_right; // How slow the ball must be moving for us to clear it from the defense area double BALL_SLOW_SPEED_THRESHOLD = 0.2; };
scveloso/Software
src/software/util/time/timestamp.h
#pragma once #include "software/util/time/duration.h" #include "software/util/time/time.h" /** * A simple Timestamp class built around doubles. This Timestamp is intended to represent * the t_capture timestamps we receive from the SSL Vision system. These t_capture values * are monotonic (meaning they are always positive and always increase), and are relative * to the "epoch time" defined by SSL Vision. This "epoch" is when SSL Vision starts up * and begins streaming data. Therefore, these timestamps are not absolute "wall clock" * time, but points in time relative to when the SSL Vision program started. They can and * should be used to timestamp all data received from SSL Vision and propagated throughout * the system in order to calculate time differences (durations), velocities, and other * time-dependent values. */ class Timestamp : public Time { public: /** * The default constructor for a Timestamp. Creates a Timestamp at time 0 */ Timestamp(); /** * Creates a new Timestamp value from a value in seconds. * @param seconds A value >= 0.0, in seconds, from which to create the Timestamp * @throws std::invalid_argument if the given value is < 0.0 * @return A Timestamp created from the given value */ static const Timestamp fromSeconds(double seconds); /** * Creates a new Timestamp value from a value in milliseconds * @param milliseconds A value >= 0.0, in milliseconds, from which to create the * Timestamp * @throws std::invalid_argument if the given value is < 0.0 * @return A Timestamp created from the given value */ static const Timestamp fromMilliseconds(double milliseconds); /** * Compares Timestamps for equality. Timestamps are considered equal if their values * in seconds are within EPSILON from one another. * * @param other the Timestamp to compare with for equality * @return true if the Timestamps are equal and false otherwise */ bool operator==(const Timestamp& other) const; /** * Compares Timestamps for inequality * * @param other the Timestamp to compare with for inequality * @return true if the Timestamps are not equal, and false otherwise */ bool operator!=(const Timestamp& other) const; /** * Defines the "less than" operator. Returns true if this Timestamp is strictly less * than (and not equal to) the other Timestamp * * @param other the Timestamp to compare with * @return true if this Timestamp is strictly less than (and not equal to) the other * Timestamp, and false otherwise */ bool operator<(const Timestamp& other) const; /** * Defines the "less than or equal to" operator. Returns true if this Timestamp is * less than or equal to the other Timestamp * * @param other the Timestamp to compare with * @return true if this Timestamp is less than or equal to the other Timestamp, and * false otherwise */ bool operator<=(const Timestamp& other) const; /** * Defines the "greater than" operator. Returns true if this Timestamp is strictly * greater than (and not equal to) the other Timestamp * * @param other the Timestamp to compare with * @return true if this Timestamp is strictly greater than (and not equal to) the * other Timestamp, and false otherwise */ bool operator>(const Timestamp& other) const; /** * Defines the "greater than or equal to" operator. Returns true if this Timestamp * is greater than or equal to the other Timestamp * * @param other the Timestamp to compare with * @return true if this Timestamp is greater than or equal to the other Timestamp, and * false otherwise */ bool operator>=(const Timestamp& other) const; /** * Defines the addition operator for Timestamps. Allows Durations to be added to * Timestamps * * @param duration the Duration to add to this Timestamp * @return A new Timestamp with the given Duration added to this Timestamp */ Timestamp operator+(const Duration& duration) const; /** * Defines the subtraction operator for Timestamps. Allows Durations to be subtracted * from Timestamps * * @param duration the Duration to subtract from this Timestamp * @return A new Timestamp with the given Duration subtracted from to this Timestamp */ Timestamp operator-(const Duration& duration) const; /** * Defines the subtraction operator for Timestamps. Allows Timestamps to be subtracted * from Timestamps * * @param timestamp The Timestamp to subtract from this Timestamp * @return A Duration that is the difference in time between the two timestamps */ Duration operator-(const Timestamp& timestamp) const; private: /** * Constructs a Timestamp value from a value in seconds. * @param timestamp_seconds A value >= 0.0, in seconds, from which to create the * timestamp * @throws std::invalid_argument if the provided value is < 0.0 */ explicit Timestamp(double timestamp_seconds); };
scveloso/Software
src/software/ai/intent/direct_wheels_intent.h
<reponame>scveloso/Software #pragma once #include "software/ai/intent/intent.h" #include "software/ai/primitive/direct_wheels_primitive.h" class DirectWheelsIntent : public Intent, public DirectWheelsPrimitive { public: static const std::string INTENT_NAME; /** * Creates a new DirectWheels Intent * * Power is a fraction of the total power we can apply to the robots, * with +-255 being the max/min, and 0 being no power. * * @param robot_id the id of the robot * @param front_left_wheel_power a value between -255 and 255, where positive is * clockwise * @param back_left_wheel_power a value between -255 and 255, where positive is * clockwise * @param front_right_wheel_power a value between -255 and 255, where positive is * clockwise * @param back_right_wheel_power a value between -255 and 255, where positive is * clockwise * @param dribbler_rpm the dribbler rpm * @param priority The priority of this Intent. A larger number indicates a higher * priority */ explicit DirectWheelsIntent(unsigned int robot_id, int16_t front_left_wheel_power, int16_t back_left_wheel_power, int16_t front_right_wheel_power, int16_t back_right_wheel_power, double dribbler_rpm, unsigned int priority); std::string getIntentName(void) const override; void accept(IntentVisitor& visitor) const override; /** * Compares DirectWheelsIntents for equality. DirectWheelsIntents are considered equal * if all their member variables are equal. * * @param other the DirectWheelsIntents to compare with for equality * @return true if the DirectWheelsIntents are equal and false otherwise */ bool operator==(const DirectWheelsIntent& other) const; /** * Compares DirectWheelsIntents for inequality. * * @param other the DirectWheelsIntent to compare with for inequality * @return true if the DirectWheelsIntents are not equal and false otherwise */ bool operator!=(const DirectWheelsIntent& other) const; };
scveloso/Software
src/software/ai/hl/hl.h
#pragma once #include <memory> #include <vector> #include "software/ai/hl/stp/play_info.h" #include "software/ai/intent/intent.h" #include "software/ai/world/world.h" /** * An abstraction for the high-level logic of our AI. The high-level logic is responsible * for the major strategic gameplay decisions of the AI. * * This is an Abstract class meant to define the interface that all HL modules must * follow. Other classes should inherit from this class and implement the methods to * create a concrete implementation of a HL module. This allows us to potentially have * multiple different high-level decision making modules, that we can swap out or combine * at runtime. */ class HL { public: /** * Given the state of the world, returns the Intent that each available Robot should * be running. * * @param world The current state of the world * * @return A vector of unique pointers to the Intents our friendly robots should be * running */ virtual std::vector<std::unique_ptr<Intent>> getIntents(const World &world) = 0; /** * Returns information about the currently running plays and tactics, including the * name of the play, and which robots are running which tactics * * @return information about the currently running plays and tactics */ virtual PlayInfo getPlayInfo() = 0; virtual ~HL() = default; };
scveloso/Software
src/software/ai/navigator/path_planning_navigator/obstacle/obstacle.h
/** * An obstacle is an area to avoid based on the size of the robot and its velocity */ #pragma once #include "shared/constants.h" #include "software/ai/world/ball.h" #include "software/ai/world/robot.h" #include "software/geom/angle.h" #include "software/geom/circle.h" #include "software/geom/point.h" #include "software/geom/polygon.h" #include "software/geom/util.h" class Obstacle { public: /** * Create an obstacle from the given polygon * * @param polygon */ Obstacle(Polygon polygon); /** * Create an obstacle from a rectangle * * @param rectangle */ Obstacle(Rectangle rectangle); /** * Create an obstacle from a circle * * @param circle */ Obstacle(Circle circle); /** * Circle obstacle defined by the given parameters * * @param circle_centre The centre point of the circle * @param circle_radius The radius of the circle * @param radius_scaling How much to scale the radius * * @return circle shaped obstacle */ static Obstacle createCircleObstacle(const Point& circle_centre, const double circle_radius, const double radius_scaling); static Obstacle createRobotObstacle(const Robot& robot, bool enable_velocity_cushion); static Obstacle createCircularRobotObstacle(const Robot& robot, double radius_cushion_scaling); /* * Gets the boundary polygon around the given primitive that other robots * should not enter with a buffer scaled by width_scaling and length_scaling * * length is along the length of the primitive and the width is perpendicular to that * * @param start start position * @param destination destination position * @param initial_speed initial speed of the robot * @param width_scaling multiplicatively scales the width of obstacle * @param length_scaling multiplicatively scales the length * * @return a rectangular Polygon to represent the boundary around the obstacle */ static Obstacle createVelocityObstacleWithScalingParams(Point start, Point end, double initial_speed, double width_scaling, double length_scaling); /* * Gets the boundary polygon around the given robot obstacle that other robots * should not enter with a buffer scaled by radius_cushion_scaling and * velocity_cushion_scaling * * The radius cushion is a hexagon such that the centre to side distance is (minimum * distance needed for two robots to clear each other * radius scaling) * * The velocity cushion is a rectangular projection whose length is (velocity * * velocity scaling) and whose width is the diameter of the radius cushion * * * @param robot robot to create obstacle boundary polygon around * @param radius_cushion_scaling multiplicatively scales the radius of the obstacle * @param velocity_cushion_scaling multiplicatively scales the cushion of * velocity of the robot * * @return a six-sided Polygon to represent the boundary around the obstacle */ static Obstacle createRobotObstacleWithScalingParams(const Robot& robot, double radius_cushion_scaling, double velocity_cushion_scaling); /* * Gets the boundary polygon around the given robot obstacle that other robots * should not enter with a buffer additively expanded by * additional_radius_cushion_buffer and additional_velocity_cushion_buffer * * The radius cushion is a hexagon such that the centre to side distance is (minimum * distance needed for two robots to clear each other + radius buffer) * * The velocity cushion is a rectangular projection whose length is (velocity + * velocity buffer) and whose width is the diameter of the radius cushion * * @param robot robot to create obstacle boundary polygon around * @param additional_radius_cushion_buffer additively increases the radius of the * obstacle by specified amount * @param additional_velocity_cushion_buffer additively increases the cushion of * velocity of the robot * @param enable_velocity_cushion if true, enables the cushion of the velocity * of the robot as component of the obstacle * * @return a six-sided Polygon to represent the boundary around the obstacle */ static Obstacle createRobotObstacleWithBufferParams( const Robot& robot, bool enable_velocity_cushion, double additional_radius_cushion_buffer, double additional_velocity_cushion_buffer); // TODO: @jonl112: plz add javadoc and unit test this static Obstacle createBallObstacle(const Ball& ball, double additional_radius_cushion_buffer, double additional_velocity_cushion_buffer); /** * Circle obstacle around ball with additional_radius_cushion_buffer * * @param ball ball to make obstacle around * @param additional_radius_cushion_buffer extra buffer around obstacle * * @return obstacle around the ball */ static Obstacle createCircularBallObstacle(const Ball& ball, double additional_radius_cushion_buffer); const std::optional<Polygon> getBoundaryPolygon() const; const std::optional<Circle> getBoundaryCircle() const; bool containsPoint(const Point& point) const; bool intersects(const Segment& segment) const; bool isPolygon() const; private: static Obstacle createRobotObstacleFromPositionAndRadiusAndVelocity( Point position, double radius_cushion, Vector velocity_cushion_vector, bool enable_velocity_cushion); static double getRadiusCushionForHexagon(double radius); std::optional<Polygon> _polygon; std::optional<Circle> _circle; }; inline std::ostream& operator<<(std::ostream& os, const Obstacle& o) { if (o.isPolygon()) { os << "Obstacle is the polygon {"; for (const Point& point : (*o.getBoundaryPolygon()).getPoints()) { os << point << ","; } os << "}"; } else { os << "Obstacle is the circle with origin " << (*o.getBoundaryCircle()).getOrigin() << " and radius " << (*o.getBoundaryCircle()).getRadius(); } return os; }
scveloso/Software
src/software/ai/hl/stp/play/corner_kick_play.h
<filename>src/software/ai/hl/stp/play/corner_kick_play.h #pragma once #include "software/ai/hl/stp/play/play.h" #include "software/ai/hl/stp/tactic/cherry_pick_tactic.h" #include "software/ai/hl/stp/tactic/move_tactic.h" /** * A Play for Corner Kicks */ class CornerKickPlay : public Play { public: static const std::string name; CornerKickPlay(); std::string getName() const override; bool isApplicable(const World &world) const override; bool invariantHolds(const World &world) const override; void getNextTactics(TacticCoroutine::push_type &yield) override; private: // The maximum distance from the corner that the ball can be for it to be // considered a corner kick static constexpr double BALL_IN_CORNER_RADIUS = 0.5; // The maximum time that we will wait before committing to a pass const Duration MAX_TIME_TO_COMMIT_TO_PASS; /** * Updates the given cherry-pick tactics * @param tactics */ void updateCherryPickTactics(std::vector<std::shared_ptr<CherryPickTactic>> tactics); /** * Update the tactic that aligns the robot to the ball in preperation to pass * * @param align_to_ball_tactic */ void updateAlignToBallTactic(std::shared_ptr<MoveTactic> align_to_ball_tactic); /** * Updates the pass generator * * @param pass_generator */ void updatePassGenerator(Passing::PassGenerator &pass_generator); };
scveloso/Software
src/software/ai/intent/pivot_intent.h
#pragma once #include "software/ai/intent/intent.h" #include "software/ai/primitive/pivot_primitive.h" #include "software/geom/angle.h" #include "software/geom/point.h" class PivotIntent : public Intent, public PivotPrimitive { public: static const std::string INTENT_NAME; /** * Creates a new Pivot Intent * * @param robot_id The id of the robot that this Intent is for * @param dest The destination of the Movement * @param final_angle The final angle the robot should have at the end of the movement * @param pivot_speed The angular speed the robot should have while it pivots * @param enable_dribbler Whether or not the dribbler should be spinning to hold the * ball * @param priority The priority of this Intent. A larger number indicates a higher * priority */ explicit PivotIntent(unsigned int robot_id, const Point& pivot_point, const Angle& final_angle, const Angle& pivot_speed, bool enable_dribbler, unsigned int priority); std::string getIntentName(void) const override; void accept(IntentVisitor& visitor) const override; /** * Compares PivotIntents for equality. PivotIntents are considered equal if all * their member variables are equal. * * @param other the PivotIntents to compare with for equality * @return true if the PivotIntents are equal and false otherwise */ bool operator==(const PivotIntent& other) const; /** * Compares PivotIntents for inequality. * * @param other the PivotIntent to compare with for inequality * @return true if the PivotIntents are not equal and false otherwise */ bool operator!=(const PivotIntent& other) const; };
scveloso/Software
src/software/ai/hl/stp/tactic/cherry_pick_tactic.h
/** * Declaration for the CherryPickTactic class */ #pragma once #include "software/ai/hl/stp/tactic/tactic.h" #include "software/ai/passing/pass_generator.h" #include "software/ai/world/world.h" #include "software/geom/rectangle.h" /** * This tactic is intended to place a robot in a given region, and have the robot * constantly move towards the best location within that region such that if we were to * pass the ball from it's current position, the robot would be in the best possible place * to receive it. */ class CherryPickTactic : public Tactic { public: /** * Creates a new CherryPickTactic */ explicit CherryPickTactic(const World& world, const Rectangle& target_region); std::string getName() const override; /** * Updates the parameters for this tactic * * @param world The current state of the world */ void updateParams(const World& world); /** * Calculates the cost of assigning the given robot to this Tactic. Prefers robots * closer to the block destination * * @param robot The robot to evaluate the cost for * @param world The state of the world with which to perform the evaluation * @return A cost in the range [0,1] indicating the cost of assigning the given robot * to this tactic. Lower cost values indicate a more preferred robot. */ double calculateRobotCost(const Robot& robot, const World& world) override; private: void calculateNextIntent(IntentCoroutine::push_type& yield) override; // The region in which we want to position the cherry picking robot Rectangle target_region; // The pass optimizer being used to figure out the best position for the robot Passing::PassGenerator pass_generator; // Tactic parameters // The current state of the world World world; };
scveloso/Software
src/software/backend/output/radio/radio_output.h
#pragma once #include <limits> #include "software/ai/world/ball.h" #include "software/ai/world/team.h" #include "software/backend/output/radio/mrf/dongle.h" #include "software/backend/robot_status.h" class RadioOutput { public: /** * Creates a new RadioOutput. * Automatically connects to the dongle upon initialization. * * @param config MRF configuration to start dongle in * @param received_robot_status_callback The callback function to call with new * robot status messages */ explicit RadioOutput(unsigned int config, std::function<void(RobotStatus)> received_robot_status_callback); /** * Sends the given primitives to the backend to control the robots * * @param primitives the list of primitives to send */ void sendPrimitives(const std::vector<std::unique_ptr<Primitive>>& primitives); /** * Sends a camera packet with the detected robots and ball. * * @param friendly_robots a vector of tuples of {robot id, robot location, * robot orientation} * @param ball */ void sendVisionPacket(std::vector<std::tuple<uint8_t, Point, Angle>> friendly_robots, Ball ball); /** * Sends a camera packet with the detected robots and ball. * * @param friendly_team * @param ball */ void sendVisionPacket(const Team& friendly_team, Ball ball); private: MRFDongle dongle; // The Annunciator that sends messages from the dongle to AI Annunciator annunciator; };
scveloso/Software
src/software/ai/navigator/path_planning_navigator/trespass.h
<reponame>scveloso/Software<filename>src/software/ai/navigator/path_planning_navigator/trespass.h #pragma once #include "software/geom/rectangle.h" namespace Navigator { namespace Trespass { /** * Returns a trespass score in the range [0, 1] for a rectangle * If the point is outside the rectangle, returns 0 * If the point is at the centre of the rectangle, returns 1 * * @param */ double calcLinearTrespassScore(Rectangle r, Point p); /** * Returns the binary trespass score of a point and rectangle * * @param point The point to check for trespassing * @param rectangle The rectangle to check for trespassing by the Point parameter * @return 1 if the point exists within the rectangle, or on the boundry of the * rectangle 0 if the point exists outside of the rectangle */ int calcBinaryTrespassScore(const Rectangle &rectangle, const Point &point); } // namespace Trespass } // namespace Navigator
scveloso/Software
src/software/backend/backend.h
#pragma once #include "software/ai/primitive/primitive.h" #include "software/ai/world/world.h" #include "software/backend/robot_status.h" #include "software/multithreading/subject.h" #include "software/multithreading/threaded_observer.h" #include "software/typedefs.h" /** * A Backend is an abstraction around all I/O operations that our system may need * to perform. It produces Worlds that may be used, and consumes primitives that * need to be sent out (generally to the robots). * * This produce/consume pattern is performed by extending both "Observer" and * "Subject". Please see the the implementation of those classes for details. */ class Backend : public Subject<World>, public Subject<RobotStatus>, public ThreadedObserver<ConstPrimitiveVectorPtr> { public: Backend() = default; virtual ~Backend() = default; // Delete the copy and assignment operators because this class really shouldn't need // them and we don't want to risk doing anything nasty with the internal // multithreading this class potentially uses Backend& operator=(const Backend&) = delete; Backend(const Backend&) = delete; };
scveloso/Software
src/firmware/main/primitives/move.c
#include "move.h" #include "control.h" #include "physics.h" #include "bangbang.h" #include "util/physbot.h" #include "shared_util/robot_constants.h" #include "shared_util/constants.h" #include "util/log.h" #include "util/util.h" #include <math.h> #include <stdio.h> #ifndef FWSIM #include "chicker.h" #include "dr.h" #include "dribbler.h" #include "leds.h" #else #include "simulate.h" #endif // these are set to decouple the 3 axis from each other // the idea is to clamp the maximum velocity and acceleration // so that the axes would never have to compete for resources #define TIME_HORIZON 0.05f //s const float PI_2 = P_PI / 2.0f; static float destination[3], end_speed, major_vec[2], minor_vec[2]; // store a wheel index here so we only have to calculate the axis // we want to use when move start is called static unsigned wheel_index; // an array to store the wheel axes in that are perpendicular to // each wheel static float wheel_axes[8]; static bool slow; /** * builds an array that contains all of the axes perpendicular to * each of the wheels on the bot. * * @param angle the current angle that the bot is facing * @return void */ static void build_wheel_axes(float angle) { wheel_axes[0] = angle + ANGLE_TO_FRONT_WHEELS - PI_2; wheel_axes[1] = angle + ANGLE_TO_FRONT_WHEELS + PI_2; wheel_axes[2] = angle - ANGLE_TO_FRONT_WHEELS - PI_2; wheel_axes[3] = angle - ANGLE_TO_FRONT_WHEELS + PI_2; wheel_axes[4] = angle + ANGLE_TO_BACK_WHEELS - PI_2; wheel_axes[5] = angle + ANGLE_TO_BACK_WHEELS - (3 * PI_2); wheel_axes[6] = angle - ANGLE_TO_BACK_WHEELS + PI_2; wheel_axes[7] = angle - ANGLE_TO_BACK_WHEELS + (3 * PI_2); } unsigned choose_wheel_axis(float dx, float dy, float current_angle, float final_angle) { build_wheel_axes(current_angle); // the angle on the global axis corresponding to the bot's movement float theta_norm = atan2f(dy, dx); // initialize a variable to store the minimum rotation float minimum_rotation = 2 * P_PI; // the index that corresponds to the minimum rotation unsigned min_index = 0; unsigned i; // loop through each axis to find the optimal one to rotate onto. // it should be the axis that is closest to our final angle for (i = 0; i < 2 * NUMBER_OF_WHEELS; i++) { float relative_angle_to_movement = min_angle_delta(wheel_axes[i], theta_norm); float initial_rotation = current_angle + relative_angle_to_movement; float abs_final_rotation = fabs(min_angle_delta(initial_rotation, final_angle)); // if we have found a smaller angle, then update the minimum rotation // and chosen index if (abs_final_rotation < minimum_rotation) { minimum_rotation = abs_final_rotation; min_index = i; } } return min_index; } /** * If we are far enough away from our destination, then we should try * rotating onto a wheel axis so that we can move faster. We should * pick the wheel axis that minimizes the distance the bot will have * to rotate to get to its destination angle after rotating onto an * axis. * * @param pb The data container that contains information about * the direction the robot will move along. * @param angle The angle that the robot is currently facing * @return void */ void choose_rotation_destination(PhysBot *pb, float angle) { // if we are close enough then we should just allow the bot to rotate // onto its destination angle, so skip this if block if ((float) fabs(pb->maj.disp) > APPROACH_LIMIT) { build_wheel_axes(angle); float theta_norm = atan2f(pb->dr[1], pb->dr[0]); // use the pre-determined wheel axis pb->rot.disp = min_angle_delta(wheel_axes[wheel_index], theta_norm); } } void plan_move_rotation(PhysBot *pb, float avel) { float time_target = (pb->maj.time > TIME_HORIZON) ? pb->maj.time : TIME_HORIZON; if (time_target > 0.5f){ time_target = 0.5f; } pb->rot.time = time_target; pb->rot.vel = pb->rot.disp / pb->rot.time; pb->rot.accel = (pb->rot.vel - avel) / TIME_HORIZON; limit(&pb->rot.accel, MAX_T_A); } /** * Pass information to be logged. * * @param log The log object. * @param time_target The time target to log * @param accel A 3 length array of {x, y, rotation} accelerations * @return void */ void move_to_log(log_record_t *log, float time_target, float accel[3]) { log_destination(log, destination); log_accel(log, accel); log_time_target(log, time_target); } // need the ifndef here so that we can ignore this code when compiling // the firmware tests #ifndef FWTEST /** * Initializes the move primitive. * * This function runs once at system startup. */ static void move_init(void) { // Currently has nothing to do } /** * Starts a movement of this type. * * This function runs each time the host computer requests to start a move * movement. * * @param params the movement parameters, which are only valid until this * function returns and must be copied into this module if needed * @return void */ static void move_start(const primitive_params_t *params) { //Parameters: destination_x [mm] // destination_y [mm] // destination_ang [centi-rad] // end_speed [millimeter/s] // Convert into m/s and rad/s because physics is in m and s printf("Move start called.\n"); destination[0] = (float) (params->params[0]) / 1000.0f; destination[1] = (float) (params->params[1]) / 1000.0f; destination[2] = (float) (params->params[2]) / 100.0f; end_speed = (float) (params->params[3]) / 1000.0f; slow = params->slow; dr_data_t current_states; dr_get(&current_states); float dx = destination[0] - current_states.x; float dy = destination[1] - current_states.y; float total_disp = sqrtf(dx * dx + dy * dy); major_vec[0] = dx / total_disp; major_vec[1] = dy / total_disp; minor_vec[0] = major_vec[0]; minor_vec[1] = major_vec[1]; rotate(minor_vec, P_PI / 2); // pick the wheel axis that will be used for faster movement wheel_index = choose_wheel_axis(dx, dy, current_states.angle, destination[2]); if(params->extra & 0x01) chicker_auto_arm(CHICKER_KICK, BALL_MAX_SPEED_METERS_PER_SECOND-1); if(params->extra & 0x02) dribbler_set_speed(16000); if(params->extra & 0x04) chicker_auto_arm(CHICKER_CHIP, 2); } /** * Ends a movement of this type. * * This function runs when the host computer requests a new movement while a * move movement is already in progress. * * @return void */ static void move_end(void) { chicker_auto_disarm(); dribbler_set_speed(0); } /** * Ticks a movement of this type. * * This function runs at the system tick rate while this primitive is active. * * @param log the log record to fill with information about the tick, or * NULL if no record is to be filled * @return void */ static void move_tick(log_record_t *log) { printf("Move tick called.\n"); // get the state of the bot dr_data_t current_states; dr_get(&current_states); // setup the PhysBot data container PhysBot pb = setup_bot(current_states, destination, major_vec, minor_vec); // choose a wheel axis to rotate onto // TODO: try to make this less jittery // choose_rotation_destination(&pb, current_states.angle); // plan major axis movement float max_major_a = 3.5; float max_major_v = slow ? 1.25 : 3.0; float major_params[3] = {end_speed, max_major_a, max_major_v}; plan_move(&pb.maj, major_params); // plan minor axis movement float max_minor_a = 1.5; float max_minor_v = 1.5; float minor_params[3] = {0, max_minor_a, max_minor_v}; plan_move(&pb.min, minor_params); // plan rotation movement plan_move_rotation(&pb, current_states.avel); float accel[3] = {0, 0, pb.rot.accel}; // rotate the accel and apply it to_local_coords(accel, pb, current_states.angle, major_vec, minor_vec); apply_accel(accel, accel[2]); if (log) { move_to_log(log, pb.rot.time, accel); } } /** * The move movement primitive. */ const primitive_t MOVE_PRIMITIVE = { .direct = false, .init = &move_init, .start = &move_start, .end = &move_end, .tick = &move_tick, }; #endif
scveloso/Software
src/software/backend/output/grsim/grsim_output.h
<gh_stars>0 #pragma once #include <boost/asio.hpp> #include <string> #include "software/ai/primitive/primitive.h" #include "software/ai/world/ball.h" #include "software/ai/world/team.h" #include "software/geom/angle.h" #include "software/geom/point.h" #include "software/proto/grSim_Packet.pb.h" class GrSimOutput { public: /** * Creates a new grSim backend * * @param network_address The IP address to publish grSim commands to * @param port The port to publish commands to */ explicit GrSimOutput(std::string network_address, unsigned short port); ~GrSimOutput(); /** * Sends the given primitives to be simulated in grSim * * @param primitives the list of primitives to send * @param friendly_team A Team object containing the latest data for the friendly team * @param ball The ball */ void sendPrimitives(const std::vector<std::unique_ptr<Primitive>>& primitives, const Team& friendly_team, const Ball& ball); /** * Creates a grSim Packet protobuf message given velocity information for a robot. * Velocities are in the Robot's local coordinate system. This function is left public * so it is easy to test. * * @param robot_id The id of the robot to send the command to * @param is_yellow Specifies if the robot to send the command to is on the * yellow team * @param robot_velocity The velocity to set for the robot, in robot coordinates. X * corresponds to "forward" from the robot's perspective, and Y corresponds to the * left of the robot. Values are in metres per second. * * X (forward) * ^ * | * | * Y <--- Robot * * @param angular_velocity The angular velocity to set for the robot, in Radians per * second. A positive value results in counter-clockwise rotation, and a negative * values result in clockwise rotation * @param kick_speed_meters_per_second How hard to kick/chip the ball, in * meters/second. If chip is false, the ball is kicked along the ground. If chip is * true, the ball is chipped in the air * @param chip Whether or not to chip the ball. If chip is true, the ball is chipped * in the air, otherwise it is kicked along the ground * @param dribbler_on Whether or not to turn on the dribbler. If dribbler_on is true, * the dribbler will be turned on, otherwise the dribbler remains off. Dribbler speed * cannot be controlled in grSim */ grSim_Packet createGrSimPacketWithRobotVelocity(unsigned int robot_id, bool is_yellow, Vector robot_velocity, AngularVelocity angular_velocity, double kick_speed_meters_per_second, bool chip, bool dribbler_on) const; /** * Sends a ball replacement grSim_packet to grSim using sendGrSimPacket * * @param position the new position of the ball * @param velocity the new velocity of the ball */ void setBallState(Point destination, Vector velocity); /** * Takes a position and velocity vector for the ball * and use these to construct a grSim_packet with a replacement command. * * @param position the new position of the ball * @param velocity the new velocity of the ball */ grSim_Packet createGrSimReplacementWithBallState(Point destination, Vector velocity); private: /** * Sends a grSim packet to grSim via UDP * * @param packet the grSim packet to send */ void sendGrSimPacket(const grSim_Packet& packet); // Variables for networking std::string network_address; unsigned short port; boost::asio::io_service io_service; boost::asio::ip::udp::socket socket; boost::asio::ip::udp::endpoint remote_endpoint; };
scveloso/Software
src/software/ai/hl/stp/tactic/receiver_tactic.h
<reponame>scveloso/Software<filename>src/software/ai/hl/stp/tactic/receiver_tactic.h /** * Interface of the ReceiverTactic */ #pragma once #include "software/ai/hl/stp/tactic/tactic.h" #include "software/ai/passing/pass.h" #include "software/geom/ray.h" /** * This tactic is for a robot receiving a pass. It should be used in conjunction with * the `PasserTactic` in order to complete the pass. * * Note that this tactic does not take into account the time the pass should occur at, * it simply tries to move to the best position to receive the pass as possible */ class ReceiverTactic : public Tactic { public: /** * Creates a new ReceiverTactic * * @param field The field the pass is running on * @param friendly_team The friendly team * @param enemy_team The enemy team * @param pass The pass this tactic should try to receive * @param ball The ball being passed * @param loop_forever Whether or not this Tactic should never complete. If true, * the tactic will be restarted every time it completes */ explicit ReceiverTactic(const Field& field, const Team& friendly_team, const Team& enemy_team, const Passing::Pass pass, const Ball& ball, bool loop_forever); std::string getName() const override; /** * Updates the parameters for this ReceiverTactic. * * @param updated_friendly_team The current state of the friendly team * @param updated_enemy_team The current state of the enemy team * @param updated_pass The pass this tactic should try to receive * @param updated_ball The ball being passed */ void updateParams(const Team& updated_friendly_team, const Team& updated_enemy_team, const Passing::Pass& updated_pass, const Ball& updated_ball); /** * Calculates the cost of assigning the given robot to this Tactic. Prefers robots * closer to the block destination * * @param robot The robot to evaluate the cost for * @param world The state of the world with which to perform the evaluation * @return A cost in the range [0,1] indicating the cost of assigning the given robot * to this tactic. Lower cost values indicate a more preferred robot. */ double calculateRobotCost(const Robot& robot, const World& world) override; /** * Calculate the angle the robot should be at in order to perform the given shot * * @param shot A Ray representing the shot we want to take * @param ball The ball we want to shoot * * @return The angle to position the robot at so that it can redirect the ball to * the shot vector at the position where the shot vector and ball velocity * vectors intersect */ static Angle getOneTimeShotDirection(const Ray& shot, const Ball& ball); /** * Get the position the receiver robot should be in, and the orientation it should * have in order to perform a one-time shot when receiving a pass. * * @param robot The receiver robot * @param ball The ball * @param best_shot_target The point the receiver robot should shoot at * @return A pair containing the position and orientation the receiver robot should * have in order to perform a one-time shot */ static std::pair<Point, Angle> getOneTimeShotPositionAndOrientation( const Robot& robot, const Ball& ball, const Point& best_shot_target); private: // The minimum proportion of open net we're shooting on vs the entire size of the net // that we require before attempting a shot static constexpr double MIN_SHOT_NET_PERCENT_OPEN = 0.3; // The maximum deflection angle that we will attempt a one-touch kick towards the // enemy goal with static constexpr Angle MAX_DEFLECTION_FOR_ONE_TOUCH_SHOT = Angle::ofDegrees(90); void calculateNextIntent(IntentCoroutine::push_type& yield) override; /** * Finds a feasible shot for the robot, if any. * * A feasible shot is one where the robot does not have to rotate to much to * take the shot, and there is a sufficient percentage of the net open for the shot. * * @return A pair of a Point to shoot at and the open angle the shot could * go through, or std::nullopt if there is no feasible shot */ std::optional<std::pair<Point, Angle>> findFeasibleShot(); // The field the pass is occuring on Field field; // The friendly team Team friendly_team; // The enemy team Team enemy_team; // The pass this tactic is executing Passing::Pass pass; // The ball being passed Ball ball; };
scveloso/Software
src/software/gui/visualizer_wrapper.h
<reponame>scveloso/Software<gh_stars>0 #pragma once #include <QtCore/QGenericArgument> #include <QtWidgets/QApplication> #include <future> #include <mutex> #include <thread> #include "software/ai/hl/stp/play_info.h" #include "software/ai/world/world.h" #include "software/backend/robot_status.h" #include "software/gui/drawing/draw_functions.h" #include "software/gui/widgets/visualizer.h" #include "software/multithreading/threaded_observer.h" /** * This class wraps our Visualizer object which is responsible for * visualizing information about our AI, and allowing users to control it. */ class VisualizerWrapper : public ThreadedObserver<World>, public ThreadedObserver<AIDrawFunction>, public ThreadedObserver<PlayInfo>, public ThreadedObserver<RobotStatus> { public: VisualizerWrapper() = delete; /** * Create a new Visualizer wrapper. The argc and argv arguments are required * to create a QApplication * * @param argc The number of arguments being passed * @param argv Keyword arguments */ explicit VisualizerWrapper(int argc, char** argv); ~VisualizerWrapper() override; /** * Returns a shared_ptr to a promise that can be waited on, and that will * be notified once the Visualizer has shut down * * @return a shared_ptr to a promise that can be waited on, and that will * be notified once the Visualizer has been shut down */ std::shared_ptr<std::promise<void>> getTerminationPromise(); private: /** * Creates a new Visualizer in a new thread and starts running it. We use * promises in order for this object to still get pointers to the newly created * QApplication and Visualizer objects so we can control them. These * objects must be created in the new thread because the QApplication must be * constructed in the thread is will run in, and the Visualizer must be * created in the same context as the QApplication (which in this case is the new * thread). * * @param argc The number of arguments being passed * @param argv Keyword arguments for the Visualizer QApplication * @param application_promise_ptr A shared_ptr to a QApplication promise that will be * set by the new thread * @param visualizer_promise_ptr A shared_ptr to a ThunderbotsVisualizer promise that * will be set by the new thread */ void createAndRunVisualizer( int argc, char** argv, std::shared_ptr<std::promise<std::shared_ptr<QApplication>>> application_promise_ptr, std::shared_ptr<std::promise<std::shared_ptr<Visualizer>>> visualizer_promise_ptr, std::shared_ptr<std::promise<void>> termination_promise_ptr); void onValueReceived(World world) override; void onValueReceived(AIDrawFunction draw_function) override; void onValueReceived(PlayInfo play_info) override; void onValueReceived(RobotStatus robot_status) override; /** * Draws all the AI information in the Visualizer. This includes visualizing the state * of the world as well as drawing the AI state we want to show, like planned * navigator paths. */ void draw(); /** * Updates the PlayInfo being displayed in the Visualizer. This shows what Play and * Tactics the AI is using. */ void updatePlayInfo(); std::mutex world_lock; std::mutex ai_lock; PlayInfo most_recent_play_info; WorldDrawFunction most_recent_world_draw_function; AIDrawFunction most_recent_ai_draw_function; std::thread run_visualizer_thread; std::shared_ptr<std::promise<void>> termination_promise_ptr; std::shared_ptr<Visualizer> visualizer; std::shared_ptr<QApplication> application; };
scveloso/Software
src/software/backend/output/radio/mrf/usb/device.h
#pragma once #include <libusb/libusb.h> #include <cstddef> #include <cstdint> #include <string> #include "software/backend/output/radio/mrf/usb/devicehandle.h" #include "software/backend/output/radio/mrf/util/noncopyable.h" namespace USB { /* Forward declaration of the libusb context */ class Context; class DeviceHandle; /** * A collection of information about a USB device. */ class Device final { public: /** * Makes a copy of a device record. * * @param[in] copyref the object to copy */ Device(const Device &copyref); /** * Destroys the device information record. */ ~Device(); /** * Assigns a device information record. * * @param[in] assgref the object to copy from * * @return this object */ Device &operator=(const Device &assgref); /** * Returns the 16-bit vendor ID from the device’s device descriptor. * * @return the vendor ID */ unsigned int vendor_id() const { return device_descriptor.idVendor; } /** * Returns the 16-bit product ID from the device’s device descriptor. * * @return the product ID */ unsigned int product_id() const { return device_descriptor.idProduct; } /** * Returns the serial number from the device’s device and string * descriptors. * * @return the serial number, or an empty string if the device does not * expose a serial number */ std::string serial_number() const; private: friend class DeviceList; friend class DeviceHandle; libusb_context *context; libusb_device *device; libusb_device_descriptor device_descriptor; explicit Device(libusb_device *device); }; /** * A list of USB devices. */ class DeviceList final : public NonCopyable { public: /** * Constructs a list of all USB devices attached to the system. * * @param[in] context the library context in which to operate */ explicit DeviceList(Context &context); /** * Frees the list of devices. */ ~DeviceList(); /** * Returns the size of the list. * * @return the number of devices in the list */ std::size_t size() const { return size_; } /** * Returns a device from the list. * * @param[in] i the index of the device to return, counting from zero * * @return the device */ Device operator[](const std::size_t i) const; private: std::size_t size_; libusb_device **devices; }; } // namespace USB
scveloso/Software
src/software/ai/intent/avoid_area.h
<reponame>scveloso/Software<filename>src/software/ai/intent/avoid_area.h #pragma once #include <ostream> /** * This enum describes the areas that an intent can choose to avoid. They serve * as an indicator to the navigator when it interprets the intents */ enum class AvoidArea { // The enemy robots and their avoid obstacles ENEMY_ROBOTS, // The box around the friendly goal FRIENDLY_DEFENSE_AREA, // The box around the enemy goal ENEMY_DEFENSE_AREA, // The box around the enemy goal, inflated by 0.2 meters for certain situations INFLATED_ENEMY_DEFENSE_AREA, // The center circle CENTER_CIRCLE, // A half meter radius around the ball HALF_METER_AROUND_BALL, // The ball itself BALL, // The enemy half of the field ENEMY_HALF, // The friendly half of the field FRIENDLY_HALF }; std::ostream& operator<<(std::ostream& os, const AvoidArea& state);
scveloso/Software
src/software/gui/widgets/main_widget.h
#pragma once #include <QtWidgets/QGraphicsScene> #include <QtWidgets/QOpenGLWidget> #include <QtWidgets/QTableWidget> #include <QtWidgets/QWidget> // This include is autogenerated by the .ui file in the same folder // The generated version will be names 'ui_<filename>.h' #include "software/ai/hl/stp/play_info.h" #include "software/backend/robot_status.h" #include "software/gui/drawing/draw_functions.h" #include "software/gui/ui/ui_main_widget.h" #include "software/gui/widgets/ai_control.h" #include "software/gui/widgets/parameters.h" #include "software/gui/widgets/robot_status.h" #include "software/gui/widgets/world_view.h" // Forward declare the name of the top-level GUI class defined in main_widget.ui namespace Ui { class AutoGeneratedMainWidget; } /** * This class acts as a wrapper widget for all the autogenerated components * defined in main_widget.ui */ class MainWidget : public QWidget { Q_OBJECT public: explicit MainWidget(QWidget* parent = nullptr); ~MainWidget(); public slots: /** * Draws all the AI information we want to display in the Visualizer. This includes * visualizing the state of the world as well as drawing the AI state we want to show, * like planned navigator paths. * * @param world_draw_function The function that tells the Visualizer how to draw the * World state * @param ai_draw_function The function that tells the Visualizer how to draw the AI * state */ void draw(WorldDrawFunction world_draw_function, AIDrawFunction ai_draw_function); /** * Updates and displays newly provided PlayInfo * * @param play_info The new PlayInfo to display */ void updatePlayInfo(const PlayInfo& play_info); /** * Updates and displays the newly provided RobotStatus. * * @param robot_status The new robot status to display */ void updateRobotStatus(const RobotStatus& robot_status); private: bool first_draw_call; // Unfortunately Qt uses raw pointers // MAKE SURE TO DELETE ANY RAW POINTERS IN THE DESTRUCTOR Ui::AutoGeneratedMainWidget* main_widget; QGraphicsScene* scene; QOpenGLWidget* glWidget; };
scveloso/Software
src/software/ai/hl/stp/action/stop_action.h
#pragma once #include "software/ai/hl/stp/action/action.h" #include "software/geom/angle.h" #include "software/geom/point.h" /** * The StopAction makes the robot stop with the option to coast */ class StopAction : public Action { public: // We consider the robot to be stopped when the magnitude of its velocity is less than // 5cm / s When robots are stationary, noise in the camera data can cause its velocity // to be non-zero, which is why we use a non-zero value here. static constexpr double ROBOT_STOPPED_SPEED_THRESHOLD_DEFAULT = 0.05; /** * Creates a new StopAction * * @param stopped_speed_threshold How slow the robot must be moving before the action * is considered done * @param loop_forever Continue yielding new Move Intents, even after we have reached * our goal */ explicit StopAction( double stopped_speed_threshold = ROBOT_STOPPED_SPEED_THRESHOLD_DEFAULT, bool loop_forever = false); /** * Returns the next Intent this StopAction wants to run, given the parameters. * * @param robot the robot that should stop * @param coast Whether or not to coast to a stop. If this is false, the robot will * try actively brake to come to a stop * * @return A unique pointer to the Intent the StopAction wants to run. * */ std::unique_ptr<Intent> updateStateAndGetNextIntent(const Robot& robot, bool coast); private: void calculateNextIntent(IntentCoroutine::push_type& yield) override; // Action parameters // Whether or not the robot should coast to a stop bool coast; // The maximum speed the robot may be moving at to be considered stopped double stopped_speed_threshold; bool loop_forever; };
scveloso/Software
src/software/backend/output/radio/mrf/usb/devicehandle.h
<reponame>scveloso/Software<filename>src/software/backend/output/radio/mrf/usb/devicehandle.h #pragma once #include <libusb/libusb.h> #include <cassert> #include <cstddef> #include <cstdint> #include <memory> #include <string> #include <vector> #include "software/backend/output/radio/mrf/util/noncopyable.h" namespace USB { /* Forward declaration of the libusb context */ class Context; extern "C" void usb_transfer_handle_completed_transfer_trampoline( libusb_transfer *transfer); /* Forward declaration of Device to prevent circular includes */ class Device; /** * A libusb device handle which can be used to communicate with a device. */ class DeviceHandle final : public NonCopyable { public: /** * Opens a handle to a device based on its vendor ID, product ID, * and, optionally, serial number. * * @param[in] context the context in which to open the handle * * @param[in] vendor_id the vendor ID of the device to open * * @param[in] product_id the product ID of the device to open * * @param[in] serial_number the serial number of the device to open, or null * to open a device with matching vendor and product ID but any serial * number */ explicit DeviceHandle(Context &context, unsigned int vendor_id, unsigned int product_id, const char *serial_number = nullptr); /** * Opens a handle to a specific device. * * @param[in] device the device to open */ explicit DeviceHandle(const Device &device); /** * Closes the device handle. * * If any outstanding asynchronous transfers are in progress, the destructor * blocks until they complete. */ ~DeviceHandle(); /** * Issues a bus reset to the device. * * The device handle should be closed after the reset is issued. */ void reset(); /** * Returns the device descriptor from the device. * * @return the device descriptor */ const libusb_device_descriptor &device_descriptor() const; /** * Returns a configuration descriptor from the device. * * @param[in] index the zero-based index of the descriptor to return * * @return the configuration descriptor */ const libusb_config_descriptor &configuration_descriptor(uint8_t index) const; /** * Returns a configuration descriptor from the device. * * @param[in] value the configuration value for the descriptor * * @return the configuration descriptor */ const libusb_config_descriptor &configuration_descriptor_by_value( uint8_t value) const; /** * Reads a string descriptor from the device. * * @param[in] index the index of the string descriptor to read * * @return the descriptor */ std::string string_descriptor(uint8_t index) const; /** * Returns the current configuration number. * * @return the configuration */ int get_configuration() const; /** * Sets the device’s configuration. * * @param[in] config the configuration number to set */ void set_configuration(int config); /** * Locks an interface so no other software can use it. * * @param[in] interface the interface number to claim */ void claim_interface(int interface); /** * Releases a locked interface. * * @param[in] interface the interface to release */ void release_interface(int interface); /** * Sets an interface into a particular alternate setting. * * @param[in] interface the interface to affect, which should be claimed * * @param[in] alternate_setting the alternate setting to switch the * interface into */ void set_interface_alt_setting(int interface, int alternate_setting); /** * Attempts to clear halt status on an IN endpoint. * * @param[in] endpoint the endpoint number to operate on */ void clear_halt_in(unsigned char endpoint); /** * Attempts to clear halt status on an OUT endpoint. * * @param[in] endpoint the endpoint number to operate on */ void clear_halt_out(unsigned char endpoint); /** * Synchronously executes a control transfer with no data stage. * * @param[in] request_type the request type field of the setup transaction * * @param[in] request the request field of the setup transaction * * @param[in] value the value field of the setup transaction * * @param[in] index the index field of the setup transaction * * @param[in] timeout the maximum length of time to let the transfer run, in * milliseconds, or zero for no timeout */ void control_no_data(uint8_t request_type, uint8_t request, uint16_t value, uint16_t index, unsigned int timeout); /** * Synchronously executes a control transfer with an inbound data * stage. * * @param[in] request_type the request type field of the setup transaction * * @param[in] request the request field of the setup transaction * * @param[in] value the value field of the setup transaction * * @param[in] index the index field of the setup transaction * * @param[out] buffer a buffer in which to store the received data * * @param[in] len the maximum number of bytes to accept from the device * * @param[in] timeout the maximum length of time to let the transfer run, in * milliseconds, or zero for no timeout * * @return the number of bytes actually sent by the device */ std::size_t control_in(uint8_t request_type, uint8_t request, uint16_t value, uint16_t index, void *buffer, std::size_t len, unsigned int timeout); /** * Synchronously executes a control transfer with an outbound data * stage. * * @param[in] request_type the request type field of the setup transaction * * @param[in] request the request field of the setup transaction * * @param[in] value the value field of the setup transaction * * @param[in] index the index field of the setup transaction * * @param[in] buffer the data to send in the data stage * * @param[in] len the number of bytes to send in the data stage * * @param[in] timeout the maximum length of time to let the transfer run, in * milliseconds, or zero for no timeout */ void control_out(uint8_t request_type, uint8_t request, uint16_t value, uint16_t index, const void *buffer, std::size_t len, unsigned int timeout); /** * Synchronously executes an inbound transfer from an interrupt * endpoint. * * @param[in] endpoint the endpoint number on which to transfer * * @param[out] data a buffer in which to store the received data * * @param[in] length the maximum number of bytes to accept from the device * * @param[in] timeout the maximum length of time to let the transfer run, in * milliseconds, or zero for no timeout * * @return the number of bytes actually sent by the device */ std::size_t interrupt_in(unsigned char endpoint, void *data, std::size_t length, unsigned int timeout); /** * Synchronously executes an outbound transfer to an interrupt * endpoint. * * @param[in] endpoint the endpoint number on which to transfer * * @param[in] data the data to send * * @param[in] length the number of bytes to send * * @param[in] timeout the maximum length of time to let the transfer run, in * milliseconds, or zero for no timeout */ void interrupt_out(unsigned char endpoint, const void *data, std::size_t length, unsigned int timeout); /** * Synchronously executes an inbound transfer from a bulk endpoint. * * @param[in] endpoint the endpoint number on which to transfer * * @param[out] data a buffer in which to store the received data * * @param[in] length the maximum number of bytes to accept from the device * * @param[in] timeout the maximum length of time to let the transfer run, in * milliseconds, or zero for no timeout * * @return the number of bytes actually sent by the device */ std::size_t bulk_in(unsigned char endpoint, void *data, std::size_t length, unsigned int timeout); /** * Mark the device as shutting down, so cancelled transfers will not * issue warnings. */ void mark_shutting_down(); private: friend class Transfer; friend class ControlNoDataTransfer; friend class ControlInTransfer; friend class InterruptOutTransfer; friend class InterruptInTransfer; friend class BulkOutTransfer; friend class BulkInTransfer; friend void usb_transfer_handle_completed_transfer_trampoline( libusb_transfer *transfer); libusb_context *context; libusb_device_handle *handle; libusb_device_descriptor device_descriptor_; std::vector<std::unique_ptr<libusb_config_descriptor, void (*)(libusb_config_descriptor *)>> config_descriptors; unsigned int submitted_transfer_count; bool shutting_down; void init_descriptors(); }; } // namespace USB
scveloso/Software
src/software/ai/intent/stop_intent.h
#pragma once #include "software/ai/intent/intent.h" #include "software/ai/primitive/stop_primitive.h" class StopIntent : public Intent, public StopPrimitive { public: static const std::string INTENT_NAME; /** * Creates a new Stop Intent * * Stops the robot with the option to coast to a stop rather than stop immediately * * @param robot_id The id of the Robot to run this Primitive * @param coast to coast to a stop or not * @param priority The priority of this Intent. A larger number indicates a higher * priority */ explicit StopIntent(unsigned int robot_id, bool coast, unsigned int priority); std::string getIntentName(void) const override; void accept(IntentVisitor& visitor) const override; /** * Compares StopIntents for equality. StopIntents are considered equal if all * their member variables are equal. * * @param other the StopIntents to compare with for equality * @return true if the StopIntents are equal and false otherwise */ bool operator==(const StopIntent& other) const; /** * Compares StopIntents for inequality. * * @param other the StopIntent to compare with for inequality * @return true if the StopIntents are not equal and false otherwise */ bool operator!=(const StopIntent& other) const; };
scveloso/Software
src/software/typedefs.h
#pragma once /** * We use this typedef to pass lists of Primitives around * * Since `std::unique_ptr<Primitive>` does not have a copy constructor, we * need to pass a `shared_ptr` to the vector. To prevent people modifiying * the vector we declare it `const` */ using ConstPrimitiveVectorPtr = std::shared_ptr<const std::vector<std::unique_ptr<Primitive>>>;
scveloso/Software
src/firmware/freertos/source/port.c
<gh_stars>0 // Stack frame format, FPU not in use: // // Hardware: // xPSR // Return address // LR // R12 // R3 // R2 // R1 // R0 // // Software: // R11 // R10 // R9 ← Here and below may be covered by stack guard. // R8 // R7 // R6 // R5 // R4 // Exception return code // Stack guard RBAR // // // // Stack frame format, FPU in use: // // Hardware: // FPSCR // S15 // S14 // S13 // S12 // S11 // S10 // S9 // S8 // S7 // S6 // S5 // S4 // S3 // S2 // S1 // S0 // xPSR // Return address // LR // R12 // R3 // R2 // R1 // R0 // // Software: // S31 // S30 // S29 // S28 // S27 // S26 // S25 // S24 // S23 // S22 // S21 // S20 // S19 // S18 // S17 // S16 // R11 // R10 // R9 ← Here and below may be covered by stack guard. // R8 // R7 // R6 // R5 // R4 // Exception return code // Stack guard RBAR #include <assert.h> #include <FreeRTOS.h> #include <exception.h> #include <inttypes.h> #include <semphr.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <task.h> #include <registers/mpu.h> #include <registers/nvic.h> #include <registers/systick.h> // Layout of the CCM itself. #define CCM_BASE 0x10000000U #define CCM_SIZE 65536U // Nesting level of critical sections. static unsigned int critical_section_nesting = 0xAAAAAAAAU; // Current task control block pointer. extern unsigned long *pxCurrentTCB; // Whether to allow portENTER_CRITICAL from an ISR. static bool relax_critical_isr_check = false; // MPU regions shared by all tasks. static const struct { uint32_t address; MPU_RASR_t rasr; } COMMON_MPU_REGIONS[] = { // 0x08000000–0x080FFFFF (length 1 MiB): Flash memory (normal, read-only, write-through cache, executable) { 0x08000000, { .XN = 0, .AP = 0b111, .TEX = 0b000, .S = 0, .C = 1, .B = 0, .SRD = 0, .SIZE = 19, .ENABLE = 1 } }, // 0x10000000–0x1000FFFF (length 64 kiB): CCM (stack) (normal, read-write, write-back write-allocate cache, not executable) { 0x10000000, { .XN = 1, .AP = 0b011, .TEX = 0b001, .S = 0, .C = 1, .B = 1, .SRD = 0, .SIZE = 15, .ENABLE = 1 } }, // 0x1FFF0000–0x1FFF7FFF (length 32 kiB): System memory including U_ID and F_SIZE (normal, read-only, write-through cache, not executable) { 0x1FFF0000, { .XN = 1, .AP = 0b111, .TEX = 0b000, .S = 0, .C = 1, .B = 0, .SRD = 0, .SIZE = 14, .ENABLE = 1 } }, // 0x20000000–0x2001FFFF (length 128 kiB): SRAM (normal, read-write, write-back write-allocate cache, not executable) { 0x20000000, { .XN = 1, .AP = 0b011, .TEX = 0b001, .S = 1, .C = 1, .B = 1, .SRD = 0, .SIZE = 16, .ENABLE = 1 } }, // 0x40000000–0x4007FFFF (length 512 kiB): Peripherals (device, read-write, not executable) using subregions: // Subregion 0 (0x40000000–0x4000FFFF): Enabled (contains APB1) // Subregion 1 (0x40010000–0x4001FFFF): Enabled (contains APB2) // Subregion 2 (0x40020000–0x4002FFFF): Enabled (contains AHB1) // Subregion 3 (0x40030000–0x4003FFFF): Disabled // Subregion 4 (0x40040000–0x4004FFFF): Disabled // Subregion 5 (0x40050000–0x4005FFFF): Disabled // Subregion 6 (0x40060000–0x4006FFFF): Disabled // Subregion 7 (0x40070000–0x4007FFFF): Disabled { 0x40000000, { .XN = 1, .AP = 0b011, .TEX = 0b000, .S = 0, .C = 0, .B = 1, .SRD = 0b11111000, .SIZE = 18, .ENABLE = 1 } }, // 0x50000000–0x5007FFFF (length 512 kiB): Peripherals (device, read-write, not executable) using subregions: // Subregion 0 (0x50000000–0x5000FFFF): Enabled (contains AHB2) // Subregion 1 (0x50010000–0x5001FFFF): Enabled (contains AHB2) // Subregion 2 (0x50020000–0x5002FFFF): Enabled (contains AHB2) // Subregion 3 (0x50030000–0x5003FFFF): Enabled (contains AHB2) // Subregion 4 (0x50040000–0x5004FFFF): Enabled (contains AHB2) // Subregion 5 (0x50050000–0x5005FFFF): Enabled (contains AHB2) // Subregion 6 (0x50060000–0x5006FFFF): Enabled (contains AHB2) // Subregion 7 (0x50070000–0x5007FFFF): Disabled { 0x50000000, { .XN = 1, .AP = 0b011, .TEX = 0b000, .S = 0, .C = 0, .B = 1, .SRD = 0b10000000, .SIZE = 18, .ENABLE = 1 } }, }; #define STACK_GUARD_MPU_REGION (sizeof(COMMON_MPU_REGIONS) / sizeof(*COMMON_MPU_REGIONS)) static const MPU_RASR_t ZERO_RASR = { .ENABLE = 0 }; unsigned long *pxPortInitialiseStack(unsigned long *tos, TaskFunction_t code, void *params) { // xTaskGenericCreate subtracts one word from TOS, then rounds down to // alignment. In our case, this means it subtracts 32 bytes. ARM CPUs in // particular have predecrement stack pointers, so that’s pointless. Fix // it, to avoid wasting space! tos += portBYTE_ALIGNMENT / sizeof(unsigned long); // Push a hardware frame. *--tos = 0x01000000UL; // xPSR *--tos = (unsigned long) code; // Return address *--tos = 0; // LR *--tos = 0; // R12 *--tos = 0; // R3 *--tos = 0; // R2 *--tos = 0; // R1 *--tos = (unsigned long) params; // R0 // Push a software frame. *--tos = 0; // R11 *--tos = 0; // R10 *--tos = 0; // R9 *--tos = 0; // R8 *--tos = 0; // R7 *--tos = 0; // R6 *--tos = 0; // R5 *--tos = 0; // R4 *--tos = 0xFFFFFFFDUL; // Exception return code *--tos = 0; // Stack guard RBAR (filled in portSETUP_TCB) return tos; } void __malloc_lock(void) { vTaskSuspendAll(); } void __malloc_unlock(void) { xTaskResumeAll(); } long xPortStartScheduler(void) { // Set SVCall, PendSV, and systick priorities. // SVCall is used to start the scheduler, but is invoked following portDISABLE_INTERRUPTS in vTaskStartScheduler. // In ARM, even synchronous interrupts obey the masking registers; in order not to be escalated to hard fault, SVCall must be of an unmasked priority. // We never use it for anythign else, so just give it priority above maximum syscall interrupt priority. // The others, PendSV and systick, are the normal kernel workhorse interrupts. SCB.SHPR2.PRI_11 = EXCEPTION_MKPRIO(EXCEPTION_GROUP_PRIO(configMAX_SYSCALL_INTERRUPT_PRIORITY) - 1U, (1U << EXCEPTION_SUB_PRIO_BITS) - 1U); SCB.SHPR3.PRI_15 = configKERNEL_INTERRUPT_PRIORITY; SCB.SHPR3.PRI_14 = configKERNEL_INTERRUPT_PRIORITY; // ARMv7-M Architecture Reference Manual A3.7.3 (Memory barriers), // Synchronization requirements for System Control Space updates, states // that a DSB followed by an ISB is necessary to ensure subsequent // instructions are executed in a manner that reflects the effect an access // to the system control space that performs a context-altering operation. asm volatile("dsb\n\tisb"); // Ensure the compiler cannot sink any non-volatile-qualified memory writes // below this point, as control flow leaves the function in a way that is // not visible to the compiler and might thus defeat the writes altogether. __atomic_signal_fence(__ATOMIC_RELEASE); // We are currently running in process mode on the main stack. // What we want to be doing is running a task in process mode on the task stack, with the main stack pointer reset to its initial value ready to handle interrupts. // What pxPortInitializeStack builds on the process stack is an exception return frame, as would be built by a PendSV. // The easiest way to take advantage of that stack structure to get the first task running is… to perform an exception return! // We can’t use PendSV, as that expects to be able to save the current context somewhere first, before loading the new context. // It also won’t fix up MSP to clean up the main stack. // Use SVCall instead, and let the SVCall handler get everything ready, clean up MSP, and then do an exception return into the first task. asm volatile("svc 0"); __builtin_unreachable(); } void portENTER_CRITICAL(void) { portDISABLE_INTERRUPTS(); ++critical_section_nesting; /* This is not the interrupt safe version of the enter critical function so assert() if it is being called from an interrupt context. Only API functions that end in "FromISR" can be used in an interrupt. Only assert if the critical nesting count is 1 to protect against recursive calls if the assert function also uses a critical section. */ if (critical_section_nesting == 1U && !relax_critical_isr_check) { unsigned int xpsr; asm volatile("mrs %[xpsr], xpsr\n\t" : [xpsr] "=r" (xpsr)); configASSERT(!(xpsr & 0xFFU)); } } void portEXIT_CRITICAL(void) { if (!--critical_section_nesting) { portENABLE_INTERRUPTS(); } } void portRELAX_CRITICAL_ISR_CHECK(void) { relax_critical_isr_check = true; } void vPortSVCHandler(void) { // These variables must be held in exactly these registers, as they are used below in the inline assembly block. register unsigned long tos asm("r0"); register unsigned long init_stack asm("r1"); // Initialize critical section nesting count. critical_section_nesting = 0U; // Enable system timer. SYSTICK.RVR = configCPU_CLOCK_HZ / configTICK_RATE_HZ - 1U; SYSTICK.CVR = 0; { SYST_CSR_t tmp = { .ENABLE = 1, .TICKINT = 1, .CLKSOURCE = 1 }; SYSTICK.CSR = tmp; } // Enable FPU and set up automatic lazy state preservation. // // Here’s how it will go down: // // In a task not using the FPU, CONTROL.FPCA will be zero, and on interrupt entry, a basic frame will be stacked. // If the ISR uses the FPU, CONTROL.FPCA will be set during that usage, which will also prepare a default context from FPDSCR for the ISR. // When the ISR returns, the exception return code will cause CONTROL.FPCA to go back to zero for the task as expected. // If the ISR doesn’t use the FPU, CONTROL.FPCA will remain zero throughout, and the exception return will work the same way. // // In a task using the FPU, on first access, CONTROL.FPCA will be set and a default context will be prepared from FPDSCR. // From that moment onward, because CONTROL.FPCA=1 and FPCCR.ASPEN=1, interrupts in that task will always stack extended frames. // However, because LSPEN=1, the extended frames will not be immediately populated; rather, on interrupt entry, LSPACT will be set. // If the ISR doesn’t use the FPU, LSPACT will remain set throughout. // When the ISR returns, the exception return code will indicate an extended frame, but LSPACT=1 will elide restoration of registers. // If the ISR does use the FPU, then on first access, the frame will be populated and LSPACT will be cleared, allowing activity to proceed. // In that case, on exception return, LSPACT=0 will trigger restoration of registers. // // Thus, time is spent saving and restoring the FP registers only in the case that both the task *and* the ISR actually use them. // // This explains ISRs, but what happens during a task switch? // // When a task not using the FPU takes a PendSV, CONTROL.FPCA will be zero, and on interrupt entry, a basic hardware frame will be stacked. // The PendSV ISR will observe that the link register indicates a basic frame, and will not touch the FP registers, stacking only a basic software frame. // // When a task not using the FPU is being resumed, the PendSV ISR will first load the link register from the basic software frame. // Observing that the link register indicates a basic hardware frame, it will conclude that the software frame is also basic and will not touch the FP registers. // The exception return will unstack the basic hardware frame and leave CONTROL.FPCA=0. // // When a task using the FPU takes a PendSV, CONTROL.FPCA will be one, and on interrupt entry, an extended hardware frame will be stacked (though not populated). // Because the extended hardware frame is not populated, LSPACT will be set. // The PendSV ISR will observe that the link register indicates an extended frame, and will stack the callee-saved FP registers into an extended software frame. // The VSTM instruction used to do this is itself an FP instruction, which thus causes the extended hardware frame to be populated and LSPACT to be cleared. // Thus, by the time the stack switch occurs, all FP registers will have been placed on the stack (half in the hardware frame and half in the software frame), and LSPACT=0. // // When a task using the FPU is being resumed, the PendSV ISR will first load the link register from the basic software frame at the beginning of the extended software frame. // The PendSV ISR will observe that the link register indicates an extended frame, and will reload the callee-saved FP registers from the extended software frame. // The subsequent exception return will unstack the extended hardware frame (restoring the remaining FP registers, since LSPACT=0) and leave CONTROL.FPCA=1. { FPCCR_t fpccr = { .LSPEN = 1, .ASPEN = 1 }; FP.CCR = fpccr; CPACR_t cpacr = CPACR; cpacr.CP10 = cpacr.CP11 = 3; CPACR = cpacr; } // Configure common MPU regions. for (size_t i = 0; i < sizeof(COMMON_MPU_REGIONS) / sizeof(*COMMON_MPU_REGIONS); ++i) { MPU_RNR_t rnr = { .REGION = i }; MPU.RNR = rnr; MPU_RBAR_t rbar = { .REGION = 0, .VALID = 0, .ADDR = COMMON_MPU_REGIONS[i].address >> 5 }; MPU.RBAR = rbar; MPU.RASR = COMMON_MPU_REGIONS[i].rasr; } // Leave MPU_RNR set to the CCM stack guard region number. Set up the RASR. // Point RBAR at zero for now, until we can load a proper value from a task // stack. { MPU_RNR_t rnr = { .REGION = STACK_GUARD_MPU_REGION }; MPU.RNR = rnr; MPU_RBAR_t rbar = { .ADDR = 0, .VALID = 0, .REGION = 0 }; MPU.RBAR = rbar; MPU_RASR_t rasr = { .XN = 1, .AP = 0, .SRD = 0, .SIZE = 4, .ENABLE = 1 }; MPU.RASR = rasr; } // Enable the MPU. { MPU_CTRL_t ctrl = { .PRIVDEFENA = 0, .HFNMIENA = 0, .ENABLE = 1, }; MPU.CTRL = ctrl; } // Ensure the compiler cannot sink any non-volatile-qualified memory writes // below this point, as control flow leaves the function in a way that is // not visible to the compiler and might thus defeat the writes altogether. __atomic_signal_fence(__ATOMIC_RELEASE); // No need to handle an extended software frame here. // Because the scheduler is just starting, no tasks have run yet. // Every task is always created, initially, with only basic frames. // We must also reset the MSP to the start of the main stack (see explanation in xPortStartScheduler). tos = *pxCurrentTCB; init_stack = *(const unsigned long *) 0x08000000; asm volatile( // Fix up MSP. "msr msp, r1\n\t" // ARMv7-M Architecture Reference Manual B1.4.6 (Special-purpose // register updates and the memory order model) states that “Except // for writes to the CONTROL register, any change to a // special-purpose register by a … MSR instruction is guaranteed … // to be visible to all instructions that appear in program order // after that CPS or MSR instruction.” Consequently, the write to // PSP is guaranteed to be visible by the time the exception return // procedure begins. // Restore software frame from process stack. "ldr r1, =0xE000ED9C\n\t" // R1 = &MPU_RBAR "ldmia r0!, {r2, lr}\n\t" "ldmia r0!, {r4-r11}\n\t" "str r2, [r1]\n\t" // Cortex-M4 Devices Generic User Guide 2.2.4 (Software ordering of // memory accesses), MPU programming, states that one must “use a // DSB followed by an ISB instruction or exception return to ensure // that the new MPU configuration is used by subsequent // instructions.” We do not care whether the new RBAR value is in // force until after we return to thread mode via the exception // return, so we can omit the ISB and rely on the // InstructionSynchronizationBarrier executed as part of the // exception return procedure. However, exception return does not // imply a DataSynchronizationBarrier, so the explicit DSB is still // needed. // // Cortex-M4 erratum 838869 also requires a DSB here. "dsb\n\t" // Set PSP and return. "msr psp, r0\n\t" // ARMv7-M Architecture Reference Manual B1.4.6 (Special-purpose // register updates and the memory order model) states that “Except // for writes to the CONTROL register, any change to a // special-purpose register by a … MSR instruction is guaranteed … // to be visible to all instructions that appear in program order // after that CPS or MSR instruction.” Consequently, the write to // PSP is guaranteed to be visible by the time the exception return // procedure begins. "bx lr\n\t" : // Note that these variables do not need placeholders in the text; they are fixed in r0 and r1 respectively by their asm constraints above. : "r" (tos), "r" (init_stack)); __builtin_unreachable(); } void vPortPendSVHandler(void) __attribute__((naked)); void vPortPendSVHandler(void) { asm volatile( // Make software frame on process stack. // See the explanation in vPortSVCHandlerImpl for how we deal with floating point registers. "mrs r0, psp\n\t" "ldr r1, =0xE000ED9C\n\t" // R1 = &MPU_RBAR "tst lr, #16\n\t" "it eq\n\t" "vstmdbeq r0!, {s16-s31}\n\t" "stmdb r0!, {r10-r11}\n\t" "ldr r2, [r1]\n\t" // Stack guard RBAR → R2 "mov r3, #0\n\t" "str r3, [r1]\n\t" // Disable stack guard // Cortex-M4 Devices Generic User Guide 2.2.4 (Software ordering of // memory accesses), MPU programming, states that one must “use a // DSB followed by an ISB instruction or exception return to ensure // that the new MPU configuration is used by subsequent // instructions.” "dsb\n\t" "isb\n\t" "stmdb r0!, {r4-r9}\n\t" "stmdb r0!, {r2, lr}\n\t" // Write new top of stack pointer into TCB. "ldr r1, =pxCurrentTCB\n\t" "ldr r1, [r1]\n\t" "str r0, [r1]\n\t" // Disable interrupts. "mov r0, %[newbasepri]\n\t" "msr basepri, r0\n\t" // ARMv7-M Architecture Reference Manual B5.2.3 (MSR instruction), // Visibility of changes, states that an MSR that increases // execution priority serializes the change to the instruction // stream, so no ISB is needed here. // Ask scheduler to pick a new task. "bl vTaskSwitchContext\n\t" // Enable interrupts. "mov r0, #0\n\t" "msr basepri, r0\n\t" // ARMv7-M Architecture Reference Manual B5.2.3 (MSR instruction), // Visibility of changes, states that an MSR that decreases // execution priority may only result in the new priority being // visible after an ISB or exception return. We will be doing an // exception return soon, and we don’t care if the new priority is // visible before that or not, so no ISB is needed here. // Read the new top of stack pointer from TCB. "ldr r0, =pxCurrentTCB\n\t" "ldr r1, =0xE000ED9C\n\t" // R1 = &MPU_RBAR "ldr r0, [r0]\n\t" "ldr r0, [r0]\n\t" // Restore software frame from process stack. "ldmia r0!, {r2, lr}\n\t" // R2 = Stack guard RBAR "ldmia r0!, {r4-r11}\n\t" "tst lr, #16\n\t" "it eq\n\t" "vldmiaeq r0!, {s16-s31}\n\t" // Enable stack guard. "str r2, [r1]\n\t" // Cortex-M4 Devices Generic User Guide 2.2.4 (Software ordering of // memory accesses), MPU programming, states that one must “use a // DSB followed by an ISB instruction or exception return to ensure // that the new MPU configuration is used by subsequent // instructions.” We do not care whether the new RBAR value is in // force until after we return to thread mode via the exception // return, so we can omit the ISB and rely on the // InstructionSynchronizationBarrier executed as part of the // exception return procedure. However, exception return does not // imply a DataSynchronizationBarrier, so the explicit DSB is still // needed. // // Cortex-M4 erratum 838869 also requires a DSB here. "dsb\n\t" // Set PSP and return. "msr psp, r0\n\t" // ARMv7-M Architecture Reference Manual B1.4.6 (Special-purpose // register updates and the memory order model) states that “Except // for writes to the CONTROL register, any change to a // special-purpose register by a … MSR instruction is guaranteed … // to be visible to all instructions that appear in program order // after that CPS or MSR instruction.” Consequently, the write to // PSP is guaranteed to be visible by the time the exception return // procedure begins. "bx lr\n\t" : : [pxCurrentTCB] "i" (&pxCurrentTCB), [newbasepri] "i" (configMAX_SYSCALL_INTERRUPT_PRIORITY)); } void vPortSysTickHandler(void) { portSET_INTERRUPT_MASK_FROM_ISR(); if(xTaskIncrementTick()) { portYIELD_FROM_ISR(); } portCLEAR_INTERRUPT_MASK_FROM_ISR(0U); EXCEPTION_RETURN_BARRIER(); } #if configASSERT_DEFINED == 1 void vPortAssertIfInterruptPriorityInvalid(void) { unsigned long current_interrupt; asm("mrs %[current_interrupt], ipsr" : [current_interrupt] "=r" (current_interrupt)); if (current_interrupt >= 16U) { // This is a normal hardware interrupt, not a fault or special CPU interrupt. // Check the priority. current_interrupt -= 16U; configASSERT((NVIC.IPR[current_interrupt / 4U] >> (current_interrupt % 4U)) >= configMAX_SYSCALL_INTERRUPT_PRIORITY); } } #endif extern inline void portYIELD(void); extern inline void portYIELD_FROM_ISR(void); extern inline void portENABLE_INTERRUPTS(void); extern inline void portDISABLE_INTERRUPTS(void); extern inline unsigned long portSET_INTERRUPT_MASK_FROM_ISR(void); extern inline void portCLEAR_INTERRUPT_MASK_FROM_ISR(unsigned long old); extern inline void portENABLE_HW_INTERRUPT(unsigned int irq); extern inline void portDISABLE_HW_INTERRUPT(unsigned int irq);
scveloso/Software
src/software/backend/output/radio/mrf/usb/transfer.h
#pragma once #include <libusb/libusb.h> #include "software/backend/output/radio/mrf/usb/devicehandle.h" #include "software/backend/output/radio/mrf/util/async_operation.h" #include "software/backend/output/radio/mrf/util/noncopyable.h" namespace USB { /* Forward declarations for C linkage */ extern "C" void usb_transfer_handle_completed_transfer_trampoline( libusb_transfer *transfer); /** * A libusb transfer. */ class Transfer : public AsyncOperation<void> { public: /** * Destroys the transfer. * * If the transfer is still executing, it will be cancelled. */ virtual ~Transfer(); /** * Sets whether stalled transfers will be retried. * * By default, stalled transfers are retried a number of times before * failing as transfers can very occasionally stall spuriously. * * @param[in] retry \c true to retry stalled transfers, or \c false to fail * on the first stall */ void retry_on_stall(bool retry) { retry_on_stall_ = retry; } /** * Checks the outcome of the transfer. * * If the transfer failed, a corresponding exception will be thrown. */ void result() const override; /** * Starts the transfer. */ void submit(); protected: friend void usb_transfer_handle_completed_transfer_trampoline( libusb_transfer *transfer); DeviceHandle &device; libusb_transfer *transfer; bool submitted_, done_; bool retry_on_stall_; unsigned int stall_retries_left; explicit Transfer(DeviceHandle &dev); void handle_completed_transfer(); }; class TransferMetadata final : public NonCopyable { public: static TransferMetadata *get(libusb_transfer *transfer) { return static_cast<TransferMetadata *>(transfer->user_data); } explicit TransferMetadata(USB::Transfer &transfer, USB::DeviceHandle &device) : transfer_(&transfer), device_(device) { } USB::Transfer *transfer() const { return transfer_; } USB::DeviceHandle &device() const { return device_; } void disown() { transfer_ = nullptr; } private: USB::Transfer *transfer_; USB::DeviceHandle &device_; }; extern "C" { void usb_transfer_handle_completed_transfer_trampoline(libusb_transfer *transfer); } } // namespace USB
scveloso/Software
src/software/test_util/test_util.h
#pragma once #include "software/ai/world/ball.h" #include "software/ai/world/field.h" #include "software/ai/world/team.h" #include "software/ai/world/world.h" namespace Test { /** * This util class is to provide utility functions to our unit test suite, * primarily for assisting with test setup (such as creating World or Field objects) */ class TestUtil { public: /** * Creates a field with the standard SSL Division B dimensions * @return a field with the standard SSL Division B dimensions */ static Field createSSLDivBField(); /** * Creates a World object with a normal SSL Division B field, default (empty) * teams with 1000 milliseconds expiry buffers, and the Ball at the center of the * field with no velocity. * * @return a World object initialized with a Division B SSL field, empty teams * with 1000 millisecond expiry buffers, and the Ball at the center of the field * with no velocity. */ static World createBlankTestingWorld(); /** * Returns a new World object with friendly robots in the positions specified * by the vector of Points. Robots will be created with consecutive increasing * id's from 0 to robot_positions.size() - 1. Any friendly robots that already * existed in the world are removed before the new ones are added. * * @param world The current world object * @param robot_positions The positions to place friendly robots in * @return A new world object with friendly robots in the given positions */ static World setFriendlyRobotPositions(World world, std::vector<Point> robot_positions, const Timestamp &timestamp); /** * Returns a new World object with enemy robots in the positions specified * by the vector of Points. Robots will be created with consecutive increasing * id's from 0 to robot_positions.size() - 1. Any enemy robots that already * existed in the world are removed before the new ones are added. * * @param world The current world object * @param robot_positions The positions to place enemy robots in * @return A new world object with enemy robots in the given positions */ static World setEnemyRobotPositions(World world, std::vector<Point> robot_positions, const Timestamp &timestamp); /** * Returns a new World object with the Ball placed in the new position * specified * * @param world The current world object * @param ball_position The new position for the ball * @return A new World object with the ball placed in the given position */ static World setBallPosition(World world, Point ball_position, Timestamp timestamp); /** * Returns a new World object with the Ball's velocity set to the new velocity * * @param world The current world object * @param ball_velocity The new velocity for the ball * @return A new World object with the ball's velocity set to the new velocity */ static World setBallVelocity(World world, Vector ball_velocity, Timestamp timestamp); /** * Returns a vector containing all Refbox game states except for * LAST_ENUM_ITEM_UNUSED * * @return A vector containing all Refbox game states except for * LAST_ENUM_ITEM_UNUSED */ static std::vector<RefboxGameState> getAllRefboxGameStates(); private: /** * Returns a new team with robots placed at the given positions. Robots in the * given team are removed before new ones are placed at the given positions, * so pre-existing robots to not persist. * * @param team The team for which to set robot positions * @param robot_positions The positions of the robots * @return A new team with robots placed at the given positions */ static Team setRobotPositionsHelper(Team team, const std::vector<Point> &robot_positions, const Timestamp &timestamp); }; } // namespace Test
scveloso/Software
src/software/ai/hl/stp/action/move_action.h
#pragma once #include "software/ai/hl/stp/action/action.h" #include "software/ai/primitive/move_primitive.h" #include "software/geom/angle.h" #include "software/geom/point.h" class MoveAction : public Action { public: // We consider the robot close to a destination when it is within 2 cm. // The robot should be able to reach within 1cm of the destination even with // camera and positioning noise static constexpr double ROBOT_CLOSE_TO_DEST_THRESHOLD = 0.02; static constexpr Angle ROBOT_CLOSE_TO_ORIENTATION_THRESHOLD = Angle::ofDegrees(2); /** * Creates a new MoveAction * * @param close_to_dest_threshold How far from the destination the robot must be * before the action is considered done * @param loop_forever Continue yielding new Move Intents, even after we have reached * our goal */ explicit MoveAction( double close_to_dest_threshold = ROBOT_CLOSE_TO_DEST_THRESHOLD, Angle close_to_orientation_threshold = ROBOT_CLOSE_TO_ORIENTATION_THRESHOLD, bool loop_forever = false); /** * Returns the next Intent this MoveAction wants to run, given the parameters. * Moves the robot in a straight line to the given destination. * * @param robot The robot to move * @param destination The destination to move to (in global coordinates) * @param final_orientation The final orientation the robot should have at * the destination * @param final_speed The final speed the robot should have at the destination * @param enable_dribbler Whether or not to enable the dribbler * @param slow Whether or not to move slow * @param autokick This will enable the "break-beam" on the robot, that will * trigger the kicker or chippper to fire as soon as the ball is in front of it * * @return A unique pointer to the Intent the MoveAction wants to run. If the * MoveAction is done, returns an empty/null pointer */ std::unique_ptr<Intent> updateStateAndGetNextIntent( const Robot& robot, Point destination, Angle final_orientation, double final_speed, bool enable_dribbler = false, bool slow = false, AutokickType autokick = NONE); private: void calculateNextIntent(IntentCoroutine::push_type& yield) override; // Action parameters Point destination; Angle final_orientation; double final_speed; bool enable_dribbler; bool slow; AutokickType autokick; double close_to_dest_threshold; Angle close_to_orientation_threshold; bool loop_forever; };
scveloso/Software
src/software/ai/navigator/path_planning_navigator/obstacle/robot_obstacle.h
#pragma once #include "software/ai/world/world.h" #include "software/geom/util.h" #include "software/util/parameter/dynamic_parameters.h" class RobotObstacle { public: /** * Constructor. * * @param robot Robot to create obstacle from. * @param avoid_dist Distance to avoid obstacle by. */ RobotObstacle(const Robot& robot, double avoid_dist); /** * Returns the violation distance of the given point inside the obstacle * boundary; 0.0 if no violation. * * @param point point to check if violating * * @return Violation distance, defined as distance from the nearest boundary * to the given point; 0.0 if no violation occured. */ double getViolationDistance(const Point& point); /** * Returns the closest Point on the obstacle boundary to the given Point that * is not inside the boundary. If the given Point does not violate the boundary, * the given Point will be returned. * * @param point Point to check for * @return A point on the boundary nearest to p if p violates the boundary, otherwise * returns p */ Point getNearestValidPoint(const Point& point); /** * TODO: This function may have to be rewritten depending on our needs later, * as part of #23: https://github.com/UBC-Thunderbots/Software/issues/23 * * Checks if the given Robot will collide with the obstacle based on the current * velocities. * * @param robot Robot to check against. * @return true if collision possible, false otherwise. */ bool willCollide(const Robot& robot); private: /** * Represents the physical footprint of the robot, with * an additional avoid distance. */ Circle boundary; /** * Segment extending from robot in direction of robot travel with length * proportional to current velocity. Used for collision avoidance. */ Segment velocity; }; /** * Creates RobotObstacles based on the friendly team robots. * * @param friendly_team The team of friendly robots. * @param avoid_dist Avoidance distance around robots in meters. * * @return Vector of all friendly robots as RobotObstacles. */ std::vector<RobotObstacle> generate_friendly_obstacles(const Team& friendly_team, double avoid_dist); /** * Creates RobotObstacles around the enemy team robots. * * @param enemy_team The team of enemy robots. * @param avoid_dist Avoidance distance around robots in meters. * * @return Vector of all enemy robots as RobotObstacles. */ std::vector<RobotObstacle> generate_enemy_obstacles(const Team& enemy_team, double avoid_dist);
scveloso/Software
src/software/ai/hl/stp/tactic/block_shot_path_tactic.h
<reponame>scveloso/Software<filename>src/software/ai/hl/stp/tactic/block_shot_path_tactic.h #pragma once #include "software/ai/hl/stp/tactic/tactic.h" /** * The BlockShotPathTactic will move the robot to block the entire friendly net from * the shot */ class BlockShotPathTactic : public Tactic { public: /** * Creates a new BlockShotPathTactic * * @param field the Field we are playing on * @param loop_forever Whether or not this Tactic should never complete. If true, the * tactic will be restarted every time it completes */ explicit BlockShotPathTactic(const Field& field, bool loop_forever = false); std::string getName() const override; /** * Updates the parameters for this BlockShotPathTactic. * * @param enemy_robot The enemy robot to block from shooting on the friendly net */ void updateParams(const Robot& enemy_robot); /** * Updates the parameters for this BlockShotPathTactic. * * @param shot_origin The origin of the shot to block */ void updateParams(const Point& shot_origin); /** * Calculates the cost of assigning the given robot to this Tactic. Prefers robots * closer to the block destination * * @param robot The robot to evaluate the cost for * @param world The state of the world with which to perform the evaluation * @return A cost in the range [0,1] indicating the cost of assigning the given robot * to this tactic. Lower cost values indicate a more preferred robot. */ double calculateRobotCost(const Robot& robot, const World& world) override; private: void calculateNextIntent(IntentCoroutine::push_type& yield) override; /** * Calculates the location to move to in order to block the shot. * @return the Point to move to in order to block the shot */ Point getBlockPosition(); // Tactic parameters // The point the shot to block will be starting from Point shot_origin; // The field we are playing on Field field; };
scveloso/Software
src/software/ai/navigator/path_planning_navigator/path_planner/theta_star_path_planner.h
#pragma once #include <bits/stdc++.h> #include <unistd.h> #include "software/ai/navigator/path_planning_navigator/path_planner/path_planner.h" #include "software/ai/world/ball.h" #include "software/ai/world/field.h" /** * ThetaStarPathPlanner uses the theta * algorithm to implement * the PathPlanner interface. * https://www.geeksforgeeks.org/a-search-algorithm/ * http://aigamedev.com/open/tutorial/theta-star-any-angle-paths/ */ class ThetaStarPathPlanner : public PathPlanner { public: /** * Constructs a theta star path planner * @param field field * @param ball ball * @param obstacles obstacles to avoid */ explicit ThetaStarPathPlanner(Field field, const std::vector<Obstacle> &obstacles); /** * Returns a path that is an optimized path between start and dest. * @param start start point * @param dest destination point * @return a vector that is the optimal path avoiding obstacles * if no valid path then return std::nullopt */ std::optional<std::vector<Point>> findPath(const Point &start, const Point &dest) override; private: typedef std::pair<int, int> CellCoordinate; typedef std::pair<double, CellCoordinate> OpenListCell; class GridCell { public: GridCell(int parent_i, int parent_j, double f, double g, double h) : parent_i_(parent_i), parent_j_(parent_j), f_(f), g_(g), h_(h) { } int parent_i_, parent_j_; double f_, g_, h_; }; /* Create an open list having information as- <f, <i, j>> where f = g + h, and i, j are the row and column index of that GridCell Note that 0 <= i <= ROW-1 & 0 <= j <= COL-1 This open list is implenented as a set of pair of pair.*/ std::set<OpenListCell> openList; // Create a closed list and initialise it to false which means // that no GridCell has been included yet // This closed list is implemented as a boolean 2D array std::vector<std::vector<bool>> closedList; // Declare a 2D array of structure to hold the details // of that GridCell std::vector<std::vector<GridCell>> cellDetails; // Description of the Grid- // true --> The cell is not blocked // false --> The cell is blocked // We update this as we go to avoid updating cells we don't use std::map<std::pair<int, int>, bool> unblocked_grid; /** * Returns if a cell is within bounds of grid * @param row y position of cell * @param col x position of cell * * @return true if cell is valid */ bool isValid(int row, int col); /** * Returns if a cell is unblocked * @param row y position of cell * @param col x position of cell * * @return true if cell is unblocked */ bool isUnBlocked(int row, int col); /** * Returns if a cell is the destination * @param row y position of cell * @param col x position of cell * @param dest destination cell * * @return true if cell is the destination */ bool isDestination(int row, int col, CellCoordinate dest); /** * Returns heuristic value of a cell * This is currently the Euclidean distance to the destination * @param row y position of cell * @param col x position of cell * @param dest destination cell * * @return Euclidean distance to dest */ double calculateHValue(int row, int col, CellCoordinate dest); /** * Traces a path from the destination back to the start * and populates a vector of points with that path * @param dest destination cell * * @return vector of points with the path from start to dest */ std::vector<Point> tracePath(CellCoordinate dest); /** * Updates the new node's fields based on the current node, destination * and the distance to the next node * and checks if destination is reached * @param pCurr current cell * @param pNext next cell to be updated * @param dest destination cell * @param currToNextNodeDist Euclidean distance between pCurr and pNext * * @return true if pNew is destination */ bool updateVertex(CellCoordinate pCurr, CellCoordinate pNew, CellCoordinate dest, double currToNextNodeDist); /** * Checks for line of sight between parent cell and new cell * @param curr_parent_i parent cell's x coordinate * @param curr_parent_j parent cell's y coordinate * @param new_pair cell to check line of sight to * * @return true if line of sight from parent to new cell */ bool lineOfSight(int curr_parent_i, int curr_parent_j, CellCoordinate new_pair); /** * Finds closest unblocked cell to currCell * @param currCell current cell * * @return closest unblocked cell to currCell * if none found, return nullopt */ std::optional<CellCoordinate> findClosestUnblockedCell(CellCoordinate currCell); /** * Finds closest valid point that's not in an obstacle to p * @param p a given point * * @return closest free point to currCell * if not blocked then return p */ Point findClosestFreePoint(Point p); /** * Checks if a point is valid and doesn't exist in any obstacles * @param p a given point * * @return if p is valid and isn't in an obstacle * */ bool isValidAndFreeOfObstacles(Point p); /** * Converts a cell in grid to a point on field * * @param row row of cell * @param col col of cell * * @return Point on field */ Point convertCellToPoint(int row, int col); /** * Converts a point on field to a cell in grid * * @param p point on field * * @return cell in grid */ CellCoordinate convertPointToCell(Point p); // if close to destination then return no path static constexpr double CLOSE_TO_DEST_THRESHOLD = 0.01; // in metres // increase in threshold to reduce oscillation static constexpr int BLOCKED_DESINATION_OSCILLATION_MITIGATION = 2; // multiples of CLOSE_TO_DEST_THRESHOLD to ignore to control oscillation // resolution for searching for unblocked point around a blocked destination static constexpr double BLOCKED_DESTINATION_SEARCH_RESOLUTION = 50.0; // number of fractions to divide 1m // only change this value static constexpr int GRID_DIVISION_FACTOR = 1; // the n in the O(n^2) algorithm :p // don't change this calculation const double SIZE_OF_GRID_CELL_IN_METERS = (ROBOT_MAX_RADIUS_METERS / GRID_DIVISION_FACTOR); Field field_; std::vector<Obstacle> obstacles_; int numRows; int numCols; };
scveloso/Software
src/software/util/math/math_functions.h
<gh_stars>0 /* * This file contains declarations for math functions */ #pragma once #include "software/geom/circle.h" #include "software/geom/point.h" #include "software/geom/rectangle.h" namespace Util { /** * Linearly maps an input value to an output value in the range [0,1] * * @param value The input value * @param offset The input value at which the linear function will return 0.5 * @param linear_width the total length required for the output value to go from 0 to * 1 */ double linear(double value, double offset, double linear_width); } // namespace Util /** * Calculates the value at the given point over a 2D sigmoid over the given rectangle * * The sigmoid constructed will approach 0 far enough outside the rectangle, and * approach 1 far enough within the rectangle. The value on the edge of the rectangle * will be 0.5 * * @param rect The rectangle over which to make sigmoid function. The width of the * the rectangle is considered to be in x, and the height in y * @param sig_width The length (in either x or y) required to cause the value of the * sigmoid to go from 0.018 to 0.982 * * @return A value in [0,1], representing the value of the 2D sigmoid function over * the given rectangle at the given point */ double rectangleSigmoid(const Rectangle& rect, const Point& point, const double& sig_width); /** * Calculates the value at the given point over a 2D sigmoid over the given circle * * The sigmoid constructed will approach 0 far enough outside the circle, and approach * 1 far enough within the circle. The value on the edge of the circle will be 0.5 * * @param circle The circle over which to make sigmoid function * @param sig_width The length required to cause the value of the sigmoid to go from * 0.018 to 0.982 across the edge of the circle * * @return A value in [0,1], representing the value of the 2D sigmoid function over * the given circle at the given point */ double circleSigmoid(const Circle& circle, const Point& point, const double& sig_width); /** * A sigmoid function with a given offset from 0 and rate of change * * By default this increases from -v to positive v, ie. y = 1 / (1+e^(-x)) * To flip the sigmoid around (ie. increasing from +v to -v), subtract it from 1 * * When using this function, it is strongly encouraged that you look at it's * implementation and go plot it, play around with the numbers a bit to really * understand what they're doing. * * @param v The value to evaluate over the sigmoid * @param offset The offset of the center of the sigmoid from 0 * @param sig_width The length (in either x or y) required to cause the value of the * sigmoid to go from 0.018 to 0.982 * * @return A value in [0,1] that is the value of the sigmoid at the value v */ double sigmoid(const double& v, const double& offset, const double& sig_width);
scveloso/Software
src/software/ai/navigator/placeholder_navigator/placeholder_navigator.h
<reponame>scveloso/Software #pragma once #include "software/ai/intent/intent.h" #include "software/ai/intent/intent_visitor.h" #include "software/ai/navigator/navigator.h" #include "software/ai/primitive/primitive.h" /** * This PlaceholderNavigator is a simple navigator that will convert the given Intents * into their respective Primitives, without doing any intelligent navigation. It is meant * to provide an example of how to implement a navigator and act as a starting point for * future navigators to build off of. */ class PlaceholderNavigator : public Navigator, public IntentVisitor { public: explicit PlaceholderNavigator() = default; std::vector<std::unique_ptr<Primitive>> getAssignedPrimitives( const World &world, const std::vector<std::unique_ptr<Intent>> &assignedIntents) override; std::vector<std::vector<Point>> getPlannedPaths() override; /** * Visits a CatchIntent to perform an operation. * * @param catch_intent The CatchIntent to visit */ void visit(const CatchIntent &catch_intent) override; /** * Visits a ChipIntent to perform an operation. * * @param chip_intent The ChipIntent to visit */ void visit(const ChipIntent &chip_intent) override; /** * Visits a DirectVelocityIntent to perform an operation. * * @param direct_velocity_intent The DirectVelocityIntent to visit */ void visit(const DirectVelocityIntent &direct_velocity_intent) override; /** * Visits a DirectWheelsIntent to perform an operation. * * @param direct_wheels_intent The DirectWheelsIntent to visit */ void visit(const DirectWheelsIntent &direct_wheels_intent) override; /** * Visits a DribbleIntent to perform an operation. * * @param dribble The DribbleIntent to visit */ void visit(const DribbleIntent &dribble_intent) override; /** * Visits a KickIntent to perform an operation. * * @param kick_intent The KickIntent to visit */ void visit(const KickIntent &kick_intent) override; /** * Visits a MoveIntent to perform an operation. * * @param move_intent The MoveIntent to visit */ void visit(const MoveIntent &move_intent) override; /** * Visits a MoveSpinIntent to perform an operation. * * @param move_spin_intent The MoveSpinIntent to visit */ void visit(const MoveSpinIntent &move_spin_intent) override; /** * Visits a PivotIntent to perform an operation. * * @param pivot_intent The PivotIntent to visit */ void visit(const PivotIntent &pivot_intent) override; /** * Visits a StopIntent to perform an operation. * * @param stop_intent The StopIntent to visit */ void visit(const StopIntent &stop_intent) override; private: // This navigators knowledge / state of the world World world; // The current Primitive the navigator has created from an Intent. // This variable is set by each `visit` function std::unique_ptr<Primitive> current_primitive; };
scveloso/Software
src/software/ai/hl/stp/evaluation/deflect_off_enemy_target.h
#pragma once #include "software/ai/world/world.h" namespace Evaluation { /* Returns the point at which the player should shoot to deflect the ball of an * enemy * to the outside of the field to get another kick/corner */ Point deflect_off_enemy_target(World world); } // namespace Evaluation
alicin/GDDropZone
GDDropZone/GDDropZone.h
// // GDDropZone.h // GDDropZone // // Created by <NAME> on 27/05/2017. // Copyright © 2017 Tavsanlar AS. All rights reserved. // #import <Cocoa/Cocoa.h> //! Project version number for GDDropZone. FOUNDATION_EXPORT double GDDropZoneVersionNumber; //! Project version string for GDDropZone. FOUNDATION_EXPORT const unsigned char GDDropZoneVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <GDDropZone/PublicHeader.h>
Bytan97/CpSpec
YelBelt/week 6/result/database.h
<filename>YelBelt/week 6/result/database.h #pragma once #include "date.h" #include <string> #include <map> #include <set> #include <unordered_set> #include <ostream> #include <functional> #include <vector> #include <algorithm> class Database { public: void Add(const Date &date, const std::string &event); void Print(std::ostream &os) const; std::string Last(Date date) const; int RemoveIf(const std::function<bool(const Date &, const std::string &)> &predicate); std::vector<std::pair<Date, std::string>> FindIf(const std::function<bool(const Date &, const std::string &)> &predicate) const; private: std::map<Date, std::set<std::string>> data_unique; std::map<Date, std::vector<std::string>> data; }; std::ostream &operator<<(std::ostream &os, const std::pair<Date, std::string> &entry);
Bytan97/CpSpec
YelBelt/week 3/decompose/bus_manager.h
<gh_stars>0 #pragma once #include <vector> #include <map> #include "responses.h" using namespace std; class BusManager { private: map<string, vector<string>> buses_to_stops, stops_to_buses; public: void AddBus(const string &bus, const vector<string> &stops); BusesForStopResponse GetBusesForStop(const string &stop) const; StopsForBusResponse GetStopsForBus(const string &bus) const; AllBusesResponse GetAllBuses() const; };
Bytan97/CpSpec
YelBelt/week 3/decompose/query.h
<gh_stars>0 #pragma once #include <string> #include <vector> #include <iostream> using namespace std; enum class QueryType { NewBus, BusesForStop, StopsForBus, AllBuses }; struct Query { QueryType type; string bus; string stop; vector<string> stops; }; //bool operator==(const Query &lhs, const Query &rhs) { // return tie(lhs.type, lhs.bus, lhs.stop, lhs.stops) == tie(rhs.type, rhs.bus, rhs.stop, rhs.stops); //} istream &operator>>(istream &is, Query &q);
Bytan97/CpSpec
YelBelt/week 6/result/node.h
#pragma once #include "date.h" #include <string> #include <memory> enum class LogicalOperation { And, Or }; enum class Comparison { Less, LessOrEqual, Greater, GreaterOrEqual, Equal, NotEqual }; class Node { public: // Node() = default; virtual bool Evaluate(const Date &date, const std::string &event) = 0; }; class EmptyNode : public Node { public: bool Evaluate(const Date &date, const std::string &event) override; }; class DateComparisonNode : public Node { public: DateComparisonNode(Comparison cmp, const Date &date); bool Evaluate(const Date &date, const std::string &event) override; private: Comparison cmp; Date node_date; }; class EventComparisonNode : public Node { public: EventComparisonNode(Comparison cmp, const std::string &event); bool Evaluate(const Date &date, const std::string &event) override; private: Comparison cmp; std::string node_event; }; class LogicalOperationNode : public Node { public: LogicalOperationNode(LogicalOperation operation, const std::shared_ptr<Node> &right, const std::shared_ptr<Node> &left); bool Evaluate(const Date &date, const std::string &event) override; private: LogicalOperation operation; std::shared_ptr<Node> right; std::shared_ptr<Node> left; };
Bytan97/CpSpec
YelBelt/week 6/result/date.h
<filename>YelBelt/week 6/result/date.h #pragma once #include <stdexcept> #include <istream> #include <iomanip> #include <iostream> #include <string> #include <set> #include <tuple> class Date { public: Date(int n_year, int n_month, int n_day); int GetYear() const; int GetMonth() const; int GetDay() const; friend bool operator==(const Date &lhs, const Date& rhs); friend bool operator!=(const Date &lhs, const Date& rhs); friend bool operator<(const Date &lhs, const Date &rhs); friend bool operator>(const Date &lhs, const Date &rhs); private: int year; int month; int day; }; Date ParseDate(std::istream &is); std::ostream& operator<<(std::ostream &os, const Date &date);
Bytan97/CpSpec
YelBelt/week 3/phone number/phone_number.h
#pragma once #include <string> #include <iostream> #include <sstream> using namespace std; class PhoneNumber { public: explicit PhoneNumber(const string &international_number); string GetCountryCode() const; string GetCityCode() const; string GetLocalNumber() const; string GetInternationalNumber() const; private: string country_code_; string city_code_; string local_number_; };
Bytan97/CpSpec
YelBelt/week 3/decompose/responses.h
<reponame>Bytan97/CpSpec #pragma once #include <string> #include <vector> #include <iostream> #include <map> using namespace std; struct BusesForStopResponse { string stop; vector<string> buses; }; ostream &operator<<(ostream &os, const BusesForStopResponse &r); struct StopsForBusResponse { string bus; vector<string> stops; map<string, vector<string>> stb; }; ostream &operator<<(ostream &os, const StopsForBusResponse &r); struct AllBusesResponse { map<string, vector<string>> bts; }; ostream &operator<<(ostream &os, const AllBusesResponse &r);
UMM-CSci-3403-Fall-2017/lab-3-c-programming-arrays-doschicos
mergesort/mergesort.c
#include <stdlib.h> #include <stdio.h> #include <stdbool.h> #include "mergesort.h" void mergeRanges(int* values, int startIndex, int midPoint, int endIndex){ int rangeSize = endIndex - startIndex; int* temp = (int*) calloc(rangeSize+1, sizeof(int)); int firstIndex = startIndex; int secondIndex = midPoint; int copyIndex = 0; while(firstIndex < midPoint && secondIndex < endIndex){ if(values[firstIndex] < values[secondIndex]){ temp[copyIndex] = values[firstIndex]; firstIndex++; }else{ temp[copyIndex] = values[secondIndex]; secondIndex++; } copyIndex++; } while (firstIndex < midPoint){ temp[copyIndex] = values[firstIndex]; copyIndex++; firstIndex++; } while(secondIndex < endIndex){ temp[copyIndex] = values[secondIndex]; copyIndex++; secondIndex++; } for(int i = 0;i < rangeSize; i++){ values[i + startIndex] = temp[i]; } free(temp); } int needsSorting(int rangeSize){ return (rangeSize >= 2); } void mergesortRange(int* values, int startIndex,int endIndex){ int rangeSize = endIndex - startIndex; if(needsSorting(rangeSize) == 1){ int midPoint = (startIndex + endIndex)/2; mergesortRange(values, startIndex, midPoint); mergesortRange(values, midPoint, endIndex); mergeRanges(values, startIndex, midPoint, endIndex); } } void mergesort(int size,int* values){ mergesortRange(values, 0, size); }
UMM-CSci-3403-Fall-2017/lab-3-c-programming-arrays-doschicos
array_merge/array_merge.c
<reponame>UMM-CSci-3403-Fall-2017/lab-3-c-programming-arrays-doschicos #include "array_merge.h" #include <stdlib.h> #include "../mergesort/mergesort.c" #include <stdio.h> int* array_merge(int num_arrays, int* sizes, int** values) { //Check to see if there are arrays in values //If not then just return an empty array if(num_arrays == 0) { int* toReturn = (int*) calloc(2, sizeof(int)); toReturn[0] = 0; return toReturn; } //Add up sizes array to see how many elements //there are that we need to add into a separate array int numberOfElements = 0; for(int i = 0; i < num_arrays; i++) { numberOfElements += sizes[i]; } //Now we put all of the elements into a new array int* allElements = (int*) calloc(numberOfElements + 1, sizeof(int)); int spotInArray = 0; for(int i = 0; i < num_arrays; i++) { for(int j = 0; j < sizes[i]; j++) { allElements[spotInArray] = values[i][j]; spotInArray++; } } //Sort with our mergesort mergesort(spotInArray, allElements); //Now we need to count up the unique values in //our sorted array. We start at 1 as the first //value in the array will always be unique int uniquesCount = 1; for(int i = 1; i < spotInArray; i++) { //To find out if an element is unique we check //if the element prior to the current element //is equal, and if it is then we know that the current //element is not unique, if not then we increment our //uniques counter if(allElements[i] != allElements[i-1]) { uniquesCount++; } } //For tomorrow: create our array to return, add uniquesCount //at start, check for uniques again however add it to our return //array, free(allElements) //Created our array in which we will return when we have it filled int* toReturn = (int*) calloc(uniquesCount + 1, sizeof(int)); //Add the count at the start and the first unique right after toReturn[0] = uniquesCount; toReturn[1] = allElements[0]; //Adds all the unique elements to our array toReturn int spotIntoReturn = 2; for(int i = 1; i < spotInArray; i++) { if(allElements[i] != allElements[i-1]) { toReturn[spotIntoReturn] = allElements[i]; spotIntoReturn++; } } //free our unused arrays free(allElements); return toReturn; }
diegomacario/Quaternion-Experiments
inc/model.h
#ifndef MODEL_H #define MODEL_H #include "shader.h" #include "mesh.h" #include "resource_manager.h" class Model { public: Model(std::vector<Mesh>&& meshes, ResourceManager<Texture>&& texManager); Model(const Model&) = delete; Model& operator=(const Model&) = delete; Model(Model&& rhs) = default; Model& operator=(Model&& rhs) = default; void render(const Shader& shader) const; private: std::vector<Mesh> mMeshes; ResourceManager<Texture> mTexManager; }; #endif
diegomacario/Quaternion-Experiments
inc/state.h
#ifndef STATE_H #define STATE_H class State { public: State() = default; virtual ~State() = default; State(const State&) = delete; State& operator=(const State&) = delete; State(State&&) = delete; State& operator=(State&&) = delete; virtual void enter() = 0; virtual void processInput(float deltaTime) = 0; virtual void update(float deltaTime) = 0; virtual void render() = 0; virtual void exit() = 0; }; #endif
diegomacario/Quaternion-Experiments
inc/texture_loader.h
<filename>inc/texture_loader.h #ifndef TEXTURE_LOADER_H #define TEXTURE_LOADER_H #include <string> #include <memory> #include "texture.h" class TextureLoader { public: TextureLoader() = default; ~TextureLoader() = default; TextureLoader(const TextureLoader&) = default; TextureLoader& operator=(const TextureLoader&) = default; TextureLoader(TextureLoader&&) = default; TextureLoader& operator=(TextureLoader&&) = default; std::shared_ptr<Texture> loadResource(const std::string& texFilePath, unsigned int wrapS = GL_REPEAT, unsigned int wrapT = GL_REPEAT, unsigned int minFilter = GL_LINEAR_MIPMAP_LINEAR, unsigned int magFilter = GL_LINEAR, bool genMipmap = true) const; private: unsigned int generateTexture(const std::unique_ptr<unsigned char, void(*)(void*)>& texData, int width, int height, int numComponents, unsigned int wrapS, unsigned int wrapT, unsigned int minFilter, unsigned int magFilter, bool genMipmap) const; }; #endif
diegomacario/Quaternion-Experiments
inc/model_loader.h
<gh_stars>10-100 #ifndef MODEL_LOADER_H #define MODEL_LOADER_H #include <unordered_map> #include "model.h" #include "resource_manager.h" class ModelLoader { public: ModelLoader() = default; ~ModelLoader() = default; ModelLoader(const ModelLoader&) = default; ModelLoader& operator=(const ModelLoader&) = default; ModelLoader(ModelLoader&&) = default; ModelLoader& operator=(ModelLoader&&) = default; std::shared_ptr<Model> loadResource(const std::string& modelFilePath) const; private: void processNodeHierarchyRecursively(const aiNode* node, const aiScene* scene, const std::string& modelDir, ResourceManager<Texture>& texManager, std::vector<Mesh>& meshes) const; std::vector<Vertex> processVertices(const aiMesh* mesh) const; std::vector<unsigned int> processIndices(const aiMesh* mesh) const; Material processMaterial(const aiMaterial* material, const std::string& modelDir, ResourceManager<Texture>& texManager) const; }; #endif
diegomacario/Quaternion-Experiments
inc/camera.h
<filename>inc/camera.h #ifndef CAMERA_H #define CAMERA_H #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> class Camera { public: Camera(glm::vec3 position, glm::vec3 worldUp, float yawInDeg, float pitchInDeg, float fieldOfViewYInDeg, float aspectRatio, float near, float far, float movementSpeed, float mouseSensitivity); ~Camera() = default; Camera(const Camera&) = default; Camera& operator=(const Camera&) = default; Camera(Camera&& rhs) noexcept; Camera& operator=(Camera&& rhs) noexcept; glm::vec3 getPosition(); glm::mat4 getViewMatrix(); glm::mat4 getPerspectiveProjectionMatrix(); glm::mat4 getPerspectiveProjectionViewMatrix(); void reposition(const glm::vec3& position, const glm::vec3& worldUp, float yawInDeg, float pitchInDeg, float fieldOfViewYInDeg); enum class MovementDirection { Forward, Backward, Left, Right }; void processKeyboardInput(MovementDirection direction, float deltaTime); void processMouseMovement(float xOffset, float yOffset); void processScrollWheelMovement(float yOffset); bool isFree() const; void setFree(bool free); private: void updateCoordinateFrame(); glm::vec3 mPosition; glm::vec3 mFront; glm::vec3 mUp; glm::vec3 mRight; glm::vec3 mWorldUp; float mYawInDeg; float mPitchInDeg; float mFieldOfViewYInDeg; float mAspectRatio; float mNear; float mFar; float mMovementSpeed; float mMouseSensitivity; bool mIsFree; glm::mat4 mViewMatrix; glm::mat4 mPerspectiveProjectionMatrix; glm::mat4 mPerspectiveProjectionViewMatrix; bool mNeedToUpdateViewMatrix; bool mNeedToUpdatePerspectiveProjectionMatrix; bool mNeedToUpdatePerspectiveProjectionViewMatrix; }; #endif
diegomacario/Quaternion-Experiments
inc/line.h
<gh_stars>0 #ifndef LINE_H #define LINE_H #include <glm/glm.hpp> #include "shader.h" #include "quat.h" class Line { public: Line(glm::vec3 startPoint, glm::vec3 endPoint, const glm::vec3& position, float angleOfRotInDeg, const glm::vec3& axisOfRot, float scalingFactor, glm::vec3 color); ~Line(); Line(const Line&) = delete; Line& operator=(const Line&) = delete; Line(Line&& rhs) noexcept; Line& operator=(Line&& rhs) noexcept; void render(const Shader& shader) const; glm::vec3 getStartPoint() const; glm::vec3 getEndPoint() const; glm::vec3 getPosition() const; void setPosition(const glm::vec3& position); float getScalingFactor() const; void setRotation(const quat& rotation); void translate(const glm::vec3& translation); void rotateByMultiplyingCurrentRotationFromTheLeft(const quat& rotation); void rotateByMultiplyingCurrentRotationFromTheRight(const quat& rotation); void scale(float scalingFactor); private: void configureVAO(glm::vec3 startPoint, glm::vec3 endPoint); void calculateModelMatrix() const; glm::vec3 mStartPoint; glm::vec3 mEndPoint; glm::vec3 mPosition; quat mRotation; float mScalingFactor; glm::vec3 mColor; mutable glm::mat4 mModelMatrix; mutable bool mCalculateModelMatrix; unsigned int mVAO; unsigned int mVBO; }; #endif
diegomacario/Quaternion-Experiments
inc/quat.h
<reponame>diegomacario/Quaternion-Experiments<gh_stars>0 #ifndef QUAT_H #define QUAT_H #include <glm/glm.hpp> #define QUAT_EPSILON 0.000001f struct quat { union { struct { float x; float y; float z; float w; }; struct { glm::vec3 vector; float scalar; }; float v[4]; }; inline quat() : x(0), y(0), z(0), w(1) { } inline quat(float _x, float _y, float _z, float _w) : x(_x), y(_y), z(_z), w(_w) {} }; quat angleAxis(float angle, const glm::vec3& axis); quat fromTo(const glm::vec3& from, const glm::vec3& to); glm::vec3 getAxis(const quat& quat); float getAngle(const quat& quat); quat operator+(const quat& a, const quat& b); quat operator-(const quat& a, const quat& b); quat operator*(const quat& a, float b); quat operator-(const quat& q); bool operator==(const quat& left, const quat& right); bool operator!=(const quat& a, const quat& b); bool sameOrientation(const quat& left, const quat& right); float dot(const quat& a, const quat& b); float lenSq(const quat& q); float len(const quat& q); void normalize(quat& q); quat normalized(const quat& q); quat conjugate(const quat& q); quat inverse(const quat& q); quat operator*(const quat& Q1, const quat& Q2); quat operator*(const quat& Q1, const quat& Q2); glm::vec3 operator*(const quat& q, const glm::vec3& v); quat mix(const quat& from, const quat& to, float t); quat nlerp(const quat& from, const quat& to, float t); quat operator^(const quat& q, float f); quat slerp(const quat& start, const quat& end, float t); quat lookRotation(const glm::vec3& direction, const glm::vec3& up); glm::mat4 quatToMat4(const quat& q); quat mat4ToQuat(const glm::mat4& m); #endif
diegomacario/Quaternion-Experiments
inc/window.h
#ifndef WINDOW_H #define WINDOW_H #include <glad/glad.h> #include <GLFW/glfw3.h> #include <bitset> // TODO: Take advantage of inlining in this class. class Window { public: Window(const std::string& title); ~Window(); Window(const Window&) = delete; Window& operator=(const Window&) = delete; Window(Window&&) = delete; Window& operator=(Window&&) = delete; bool initialize(); bool shouldClose() const; void setShouldClose(bool shouldClose); // TODO: Could this be considered to be const? void swapBuffers(); // TODO: Could this be considered to be const? void pollEvents(); // TODO: Could this be considered to be const? // Window unsigned int getWidthOfWindowInPix() const; unsigned int getHeightOfWindowInPix() const; unsigned int getWidthOfFramebufferInPix() const; unsigned int getHeightOfFramebufferInPix() const; bool isFullScreen() const; void setFullScreen(bool fullScreen); // Keyboard bool keyIsPressed(int key) const; bool keyHasBeenProcessed(int key) const; void setKeyAsProcessed(int key); // Cursor bool mouseMoved() const; void resetMouseMoved(); void resetFirstMove(); float getCursorXOffset() const; float getCursorYOffset() const; void enableCursor(bool enable); // Scroll wheel bool scrollWheelMoved() const; void resetScrollWheelMoved(); float getScrollYOffset() const; // Anti aliasing support bool configureAntiAliasingSupport(); bool createMultisampleFramebuffer(); void clearAndBindMultisampleFramebuffer(); void generateAntiAliasedImage(); void resizeFramebuffers(); void setNumberOfSamples(unsigned int numOfSamples); private: void setInputCallbacks(); void framebufferSizeCallback(GLFWwindow* window, int width, int height); void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods); void cursorPosCallback(GLFWwindow* window, double xPos, double yPos); void scrollCallback(GLFWwindow* window, double xOffset, double yOffset); // Window GLFWwindow* mWindow; int mWidthOfWindowInPix; int mHeightOfWindowInPix; int mWidthOfFramebufferInPix; int mHeightOfFramebufferInPix; std::string mTitle; bool mIsFullScreen; // Keyboard std::bitset<GLFW_KEY_LAST + 1> mKeys; std::bitset<GLFW_KEY_LAST + 1> mProcessedKeys; // Cursor bool mMouseMoved; bool mFirstCursorPosCallback; double mLastCursorXPos; double mLastCursorYPos; float mCursorXOffset; float mCursorYOffset; // Scroll wheel bool mScrollWheelMoved; float mScrollYOffset; // Anti aliasing support unsigned int mMultisampleFBO; unsigned int mMultisampleTexture; unsigned int mMultisampleRBO; unsigned int mNumOfSamples; }; #endif
diegomacario/Quaternion-Experiments
inc/texture.h
#ifndef TEXTURE_H #define TEXTURE_H #include <glad/glad.h> class Texture { public: explicit Texture(unsigned int texID); ~Texture(); Texture(const Texture&) = delete; Texture& operator=(const Texture&) = delete; Texture(Texture&& rhs) noexcept; Texture& operator=(Texture&& rhs) noexcept; void bind() const; private: unsigned int mTexID; }; #endif
diegomacario/Quaternion-Experiments
inc/game_object_3D.h
#ifndef GAME_OBJECT_3D_H #define GAME_OBJECT_3D_H #include <glm/glm.hpp> #include <memory> #include "model.h" #include "quat.h" class GameObject3D { public: GameObject3D(const std::shared_ptr<Model>& model, const glm::vec3& position, float angleOfRotInDeg, const glm::vec3& axisOfRot, float scalingFactor); ~GameObject3D() = default; GameObject3D(const GameObject3D&) = default; GameObject3D& operator=(const GameObject3D&) = default; GameObject3D(GameObject3D&& rhs) noexcept; GameObject3D& operator=(GameObject3D&& rhs) noexcept; void render(const Shader& shader) const; glm::vec3 getPosition() const; void setPosition(const glm::vec3& position); float getScalingFactor() const; void setRotation(const quat& rotation); void translate(const glm::vec3& translation); void rotateByMultiplyingCurrentRotationFromTheLeft(const quat& rotation); void rotateByMultiplyingCurrentRotationFromTheRight(const quat& rotation); void scale(float scalingFactor); private: void calculateModelMatrix() const; std::shared_ptr<Model> mModel; glm::vec3 mPosition; quat mRotation; float mScalingFactor; mutable glm::mat4 mModelMatrix; mutable bool mCalculateModelMatrix; }; #endif
diegomacario/Quaternion-Experiments
inc/play_state.h
#ifndef PLAY_STATE_H #define PLAY_STATE_H #include <array> #include "game.h" #include "line.h" class PlayState : public State { public: PlayState(const std::shared_ptr<FiniteStateMachine>& finiteStateMachine, const std::shared_ptr<Window>& window, const std::shared_ptr<Camera>& camera, const std::shared_ptr<Shader>& gameObject3DShader, const std::shared_ptr<Shader>& lineShader, const std::shared_ptr<GameObject3D>& table, const std::shared_ptr<GameObject3D>& teapot); ~PlayState() = default; PlayState(const PlayState&) = delete; PlayState& operator=(const PlayState&) = delete; PlayState(PlayState&&) = delete; PlayState& operator=(PlayState&&) = delete; void enter() override; void processInput(float deltaTime) override; void update(float deltaTime) override; void render() override; void exit() override; private: void resetScene(); void resetCamera(); void rotateSceneByMultiplyingCurrentRotationFromTheLeft(const quat& rot); void rotateSceneByMultiplyingCurrentRotationFromTheRight(const quat& rot); std::shared_ptr<FiniteStateMachine> mFSM; std::shared_ptr<Window> mWindow; std::shared_ptr<Camera> mCamera; std::shared_ptr<Shader> mGameObject3DShader; std::shared_ptr<Shader> mLineShader; std::shared_ptr<GameObject3D> mTable; std::shared_ptr<GameObject3D> mTeapot; Line mWorldXAxis; Line mWorldYAxis; Line mWorldZAxis; Line mLocalXAxis; Line mLocalYAxis; Line mLocalZAxis; }; #endif
diegomacario/Quaternion-Experiments
inc/mesh.h
<reponame>diegomacario/Quaternion-Experiments #ifndef MESH_H #define MESH_H #include <assimp/scene.h> #include <memory> #include <vector> #include <bitset> #include "shader.h" #include "texture.h" struct Vertex { Vertex(const glm::vec3& position, const glm::vec3& normal, const glm::vec2& texCoords) : position(position) , normal(normal) , texCoords(texCoords) { } ~Vertex() = default; Vertex(const Vertex&) = default; Vertex& operator=(const Vertex&) = default; Vertex(Vertex&& rhs) noexcept : position(std::exchange(rhs.position, glm::vec3(0.0f))) , normal(std::exchange(rhs.normal, glm::vec3(0.0f))) , texCoords(std::exchange(rhs.texCoords, glm::vec2(0.0f))) { } Vertex& operator=(Vertex&& rhs) noexcept { position = std::exchange(rhs.position, glm::vec3(0.0f)); normal = std::exchange(rhs.normal, glm::vec3(0.0f)); texCoords = std::exchange(rhs.texCoords, glm::vec2(0.0f)); return *this; } glm::vec3 position; glm::vec3 normal; glm::vec2 texCoords; }; struct MaterialTexture { MaterialTexture(const std::shared_ptr<Texture>& texture, const std::string& uniformName) : texture(texture) , uniformName(uniformName) { } ~MaterialTexture() = default; MaterialTexture(const MaterialTexture&) = default; MaterialTexture& operator=(const MaterialTexture&) = default; MaterialTexture(MaterialTexture&& rhs) = default; MaterialTexture& operator=(MaterialTexture&& rhs) = default; std::shared_ptr<Texture> texture; std::string uniformName; }; enum class MaterialTextureTypes : unsigned int { ambient = 0, emissive = 1, diffuse = 2, specular = 3, count = 4 }; struct MaterialConstants { MaterialConstants(const glm::vec3& ambientColor, const glm::vec3& emissiveColor, const glm::vec3& diffuseColor, const glm::vec3& specularColor, float shininess) : ambientColor(ambientColor) , emissiveColor(emissiveColor) , diffuseColor(diffuseColor) , specularColor(specularColor) , shininess(shininess) { } ~MaterialConstants() = default; MaterialConstants(const MaterialConstants&) = default; MaterialConstants& operator=(const MaterialConstants&) = default; MaterialConstants(MaterialConstants&& rhs) noexcept : ambientColor(std::exchange(rhs.ambientColor, glm::vec3(0.0f))) , emissiveColor(std::exchange(rhs.emissiveColor, glm::vec3(0.0f))) , diffuseColor(std::exchange(rhs.diffuseColor, glm::vec3(0.0f))) , specularColor(std::exchange(rhs.specularColor, glm::vec3(0.0f))) , shininess(std::exchange(rhs.shininess, 0.0f)) { } MaterialConstants& operator=(MaterialConstants&& rhs) noexcept { ambientColor = std::exchange(rhs.ambientColor, glm::vec3(0.0f)); emissiveColor = std::exchange(rhs.emissiveColor, glm::vec3(0.0f)); diffuseColor = std::exchange(rhs.diffuseColor, glm::vec3(0.0f)); specularColor = std::exchange(rhs.specularColor, glm::vec3(0.0f)); shininess = std::exchange(rhs.shininess, 0.0f); return *this; } glm::vec3 ambientColor; glm::vec3 emissiveColor; glm::vec3 diffuseColor; glm::vec3 specularColor; float shininess; }; struct Material { Material(const std::vector<MaterialTexture>& materialTextures, std::bitset<static_cast<unsigned int>(MaterialTextureTypes::count)> materialTextureAvailabilities, const MaterialConstants& materialConstants) : textures(materialTextures) , textureAvailabilities(materialTextureAvailabilities) , constants(materialConstants) { } ~Material() = default; Material(const Material&) = default; Material& operator=(const Material&) = default; Material(Material&& rhs) noexcept : textures(std::move(rhs.textures)) , textureAvailabilities(std::exchange(rhs.textureAvailabilities, std::bitset<static_cast<unsigned int>(MaterialTextureTypes::count)>())) // TODO: Investigate what happens when you move a std::bitset , constants(std::move(rhs.constants)) { } Material& operator=(Material&& rhs) noexcept { textures = std::move(rhs.textures); textureAvailabilities = std::exchange(rhs.textureAvailabilities, std::bitset<static_cast<unsigned int>(MaterialTextureTypes::count)>()); // TODO: Investigate what happens when you move a std::bitset constants = std::move(rhs.constants); return *this; } std::vector<MaterialTexture> textures; std::bitset<static_cast<unsigned int>(MaterialTextureTypes::count)> textureAvailabilities; MaterialConstants constants; }; class Mesh { public: Mesh(const std::vector<Vertex>& vertices, const std::vector<unsigned int>& indices, const Material& material); ~Mesh(); Mesh(const Mesh&) = delete; Mesh& operator=(const Mesh&) = delete; Mesh(Mesh&& rhs) noexcept; Mesh& operator=(Mesh&& rhs) noexcept; void render(const Shader& shader) const; private: void configureVAO(const std::vector<Vertex>& vertices, const std::vector<unsigned int>& indices); void bindMaterialTextures(const Shader& shader) const; void setMaterialTextureAvailabilities(const Shader& shader) const; void setMaterialConstants(const Shader& shader) const; unsigned int mNumIndices; Material mMaterial; unsigned int mVAO; unsigned int mVBO; unsigned int mEBO; }; #endif
diegomacario/Quaternion-Experiments
inc/game.h
#ifndef GAME_H #define GAME_H #include "model.h" #include "game_object_3D.h" #include "camera.h" #include "window.h" #include "state.h" #include "finite_state_machine.h" class Game { public: Game(); ~Game(); Game(const Game&) = delete; Game& operator=(const Game&) = delete; Game(Game&&) = delete; Game& operator=(Game&&) = delete; bool initialize(const std::string& title); void executeGameLoop(); private: std::shared_ptr<FiniteStateMachine> mFSM; std::shared_ptr<Window> mWindow; std::shared_ptr<Camera> mCamera; ResourceManager<Model> mModelManager; ResourceManager<Texture> mTextureManager; ResourceManager<Shader> mShaderManager; std::shared_ptr<GameObject3D> mTable; std::shared_ptr<GameObject3D> mTeapot; }; #endif
diegomacario/Quaternion-Experiments
inc/shader_loader.h
<filename>inc/shader_loader.h #ifndef SHADER_LOADER_H #define SHADER_LOADER_H #include <memory> #include "shader.h" class ShaderLoader { public: ShaderLoader() = default; ~ShaderLoader() = default; ShaderLoader(const ShaderLoader&) = default; ShaderLoader& operator=(const ShaderLoader&) = default; ShaderLoader(ShaderLoader&&) = default; ShaderLoader& operator=(ShaderLoader&&) = default; std::shared_ptr<Shader> loadResource(const std::string& vShaderFilePath, const std::string& fShaderFilePath) const; std::shared_ptr<Shader> loadResource(const std::string& vShaderFilePath, const std::string& fShaderFilePath, const std::string& gShaderFilePath) const; private: unsigned int createAndCompileShader(const std::string& shaderFilePath, GLenum shaderType) const; unsigned int createAndLinkShaderProgram(unsigned int vShaderID, unsigned int fShaderID) const; unsigned int createAndLinkShaderProgram(unsigned int vShaderID, unsigned int fShaderID, unsigned int gShaderID) const; void checkForCompilationErrors(unsigned int shaderID, GLenum shaderType, const std::string& shaderFilePath) const; void checkForLinkingErrors(unsigned int shaderProgID) const; }; #endif
diegomacario/Quaternion-Experiments
inc/resource_manager.h
#ifndef RESOURCE_MANAGER_H #define RESOURCE_MANAGER_H #include <memory> #include <unordered_map> #include <iostream> template<typename TResource> class ResourceManager { public: ResourceManager() = default; ~ResourceManager() = default; ResourceManager(const ResourceManager&) = delete; ResourceManager& operator=(const ResourceManager&) = delete; ResourceManager(ResourceManager&&) = default; ResourceManager& operator=(ResourceManager&&) = default; template<typename TResourceLoader, typename... Args> std::shared_ptr<TResource> loadResource(const std::string& resourceID, Args&&... args); template<typename TResourceLoader, typename... Args> std::shared_ptr<TResource> loadUnmanagedResource(Args&&... args) const; std::shared_ptr<TResource> getResource(const std::string& resourceID) const; bool containsResource(const std::string& resourceID) const noexcept; void stopManagingResource(const std::string& resourceID) noexcept; void stopManagingAllResources() noexcept; private: std::unordered_map<std::string, std::shared_ptr<TResource>> mResources; }; template<typename TResource> template<typename TResourceLoader, typename... Args> std::shared_ptr<TResource> ResourceManager<TResource>::loadResource(const std::string& resourceID, Args&&... args) { std::shared_ptr<TResource> resource{}; auto it = mResources.find(resourceID); if (it == mResources.cend()) { resource = TResourceLoader{}.loadResource(std::forward<Args>(args)...); // We only store the resource if it is not a nullptr // We expect the loaders to print an error message when they are unable to load a resource successfully, which is why we don't print anything here if (resource) { mResources[resourceID] = resource; } } else { std::cout << "Warning - ResourceManager::loadResource - A resource with the following ID already exists: " << resourceID << "\n"; resource = it->second; } return resource; } template<typename TResource> template<typename TResourceLoader, typename... Args> std::shared_ptr<TResource> ResourceManager<TResource>::loadUnmanagedResource(Args&&... args) const { // We expect the loaders to print an error message when they are unable to load a resource successfully, which is why we don't print anything here return TResourceLoader{}.loadResource(std::forward<Args>(args)...); } template<typename TResource> std::shared_ptr<TResource> ResourceManager<TResource>::getResource(const std::string& resourceID) const { auto it = mResources.find(resourceID); if (it != mResources.end()) { return it->second; } else { std::cout << "Error - ResourceManager::getResource - A resource with the following ID does not exist: " << resourceID << "\n"; return nullptr; } } template<typename TResource> bool ResourceManager<TResource>::containsResource(const std::string& resourceID) const noexcept { return (mResources.find(resourceID) != mResources.cend()); } template<typename TResource> void ResourceManager<TResource>::stopManagingResource(const std::string& resourceID) noexcept { auto it = mResources.find(resourceID); if (it != mResources.end()) { mResources.erase(it); } else { std::cout << "Error - ResourceManager::stopManagingResource - A resource with the following ID does not exist: " << resourceID << "\n"; } } template<typename TResource> void ResourceManager<TResource>::stopManagingAllResources() noexcept { mResources.clear(); } #endif
diegomacario/Quaternion-Experiments
inc/shader.h
<reponame>diegomacario/Quaternion-Experiments<filename>inc/shader.h<gh_stars>100-1000 #ifndef SHADER_H #define SHADER_H #include <glad/glad.h> #include <glm/glm.hpp> #include <string> class Shader { public: explicit Shader(unsigned int shaderProgID); ~Shader(); Shader(const Shader&) = delete; Shader& operator=(const Shader&) = delete; Shader(Shader&& rhs) noexcept; Shader& operator=(Shader&& rhs) noexcept; void use() const; unsigned int getID() const; void setBool(const std::string& name, bool value) const; void setInt(const std::string& name, int value) const; void setFloat(const std::string& name, float value) const; void setVec2(const std::string& name, const glm::vec2& value) const; void setVec2(const std::string& name, float x, float y) const; void setVec3(const std::string& name, const glm::vec3& value) const; void setVec3(const std::string& name, float x, float y, float z) const; void setVec4(const std::string& name, const glm::vec4& value) const; void setVec4(const std::string& name, float x, float y, float z, float w) const; void setMat2(const std::string& name, const glm::mat2& value) const; void setMat3(const std::string& name, const glm::mat3& value) const; void setMat4(const std::string& name, const glm::mat4& value) const; private: int getUniformLocation(const std::string& name) const; unsigned int mShaderProgID; }; #endif
diegomacario/Quaternion-Experiments
inc/finite_state_machine.h
<reponame>diegomacario/Quaternion-Experiments #ifndef FINITE_STATE_MACHINE_H #define FINITE_STATE_MACHINE_H #include <unordered_map> #include <memory> #include "state.h" class FiniteStateMachine { public: FiniteStateMachine() = default; ~FiniteStateMachine() = default; FiniteStateMachine(const FiniteStateMachine&) = delete; FiniteStateMachine& operator=(const FiniteStateMachine&) = delete; FiniteStateMachine(FiniteStateMachine&&) = delete; FiniteStateMachine& operator=(FiniteStateMachine&&) = delete; void initialize(std::unordered_map<std::string, std::shared_ptr<State>>&& states, const std::string& initialStateID); void processInputInCurrentState(float deltaTime) const; void updateCurrentState(float deltaTime) const; void renderCurrentState() const; void changeState(const std::string& newStateID); std::shared_ptr<State> getPreviousState(); std::string getPreviousStateID() const; std::string getCurrentStateID() const; private: std::unordered_map<std::string, std::shared_ptr<State>> mStates; std::shared_ptr<State> mCurrentState; std::string mPreviousStateID; std::string mCurrentStateID; }; #endif
digaru19/MIPS_Emulator
Qt/mainwindow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QStringListModel> #include <QLineEdit> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); void display_register_values(); void read_register_values(); void read_UI_reg(QLineEdit *, int ); void allow_reg_edit(bool); void reset_reg_values(); private slots: void on_next_instr_clicked(); void on_pushButton_clicked(); void on_begin_execution_clicked(); void on_reset_reg_values_clicked(); void on_stop_execution_clicked(); private: Ui::MainWindow *ui; QStringListModel *model; }; #endif // MAINWINDOW_H
digaru19/MIPS_Emulator
src/instructions.h
<filename>src/instructions.h #ifndef MIPS_INSTRUCTIONS_SET_H #define MIPS_INSTRUCTIONS_SET_H #include "datapath_elements.h" #include <vector> #include <string> #include <string.h> #include <stdlib.h> using namespace std; class Instruction_Set { public: virtual void execute() = 0; static Instruction_Set *create_instr_obj(string , vector<string>& ); string instr; Instruction_Set() { instr.resize(35); }; }; class add : public Instruction_Set { int src_reg1,src_reg2,dest_reg; public: add(string,string,string,string); void execute(); }; class addi : public Instruction_Set { int src_reg,value,dest_reg; public: addi(string,string,string,string); void execute(); }; class _and : public Instruction_Set { int src_reg1,src_reg2,dest_reg; public: _and(string,string,string,string); void execute(); }; class _andi : public Instruction_Set { int src_reg,value,dest_reg; public: _andi(string,string,string,string); void execute(); }; class beq : public Instruction_Set { int reg_1,reg_2,target; public: beq(string,string,string,string); void execute(); }; class bne : public Instruction_Set { int reg_1,reg_2,target; public: bne(string,string,string,string); void execute(); }; class bgez : public Instruction_Set { int reg_1,target; public: bgez(string,string,string); void execute(); }; class blez : public Instruction_Set { int reg_1,target; public: blez(string,string,string); void execute(); }; class bgtz : public Instruction_Set { int reg_1,target; public: bgtz(string,string,string); void execute(); }; class bltz : public Instruction_Set { int reg_1,target; public: bltz(string,string,string); void execute(); }; class bgezal : public Instruction_Set { int reg_1,target; public: bgezal(string,string,string); void execute(); }; class bltzal : public Instruction_Set { int reg_1,target; public: bltzal(string,string,string); void execute(); }; class _div : public Instruction_Set { int divisor_reg,divident_reg; public: _div(string,string,string); void execute(); }; class divu : public Instruction_Set { int divisor_reg,divident_reg; public: divu(string,string,string); void execute(); }; class j : public Instruction_Set { int target; public: j(string,string); void execute(); }; class jr : public Instruction_Set { int src_reg; public: jr(string,string); void execute(); }; class jal : public Instruction_Set { int target; public: jal(string,string); void execute(); }; class lw: public Instruction_Set { int offset,base,reg_dest; public: lw(string,string,string,string); void execute(); }; class mult : public Instruction_Set { int multiplicand_reg,multiplier_reg; public: mult(string,string,string); void execute(); }; class multu : public Instruction_Set { int multiplicand_reg,multiplier_reg; public: multu(string,string,string); void execute(); }; class mfhi : public Instruction_Set { int dest_reg; public: mfhi(string,string); void execute(); }; class mflo : public Instruction_Set { int dest_reg; public: mflo(string,string); void execute(); }; class _or : public Instruction_Set { int src_reg1,src_reg2,dest_reg; public: _or(string,string,string,string); void execute(); }; class _ori : public Instruction_Set { int src_reg,value,dest_reg; public: _ori(string,string,string,string); void execute(); }; class sw: public Instruction_Set { int offset,base,src_reg; public: sw(string,string,string,string); void execute(); }; class sll : public Instruction_Set { int src_reg,shamt,dest_reg; public: sll(string,string,string,string); void execute(); }; class srl : public Instruction_Set { int src_reg,shamt,dest_reg; public: srl(string,string,string,string); void execute(); }; class srlv : public Instruction_Set { int src_reg,shamt_reg,dest_reg; public: srlv(string,string,string,string); void execute(); }; class sllv : public Instruction_Set { int src_reg,shamt_reg,dest_reg; public: sllv(string,string,string,string); void execute(); }; class sra : public Instruction_Set { int src_reg,shamt,dest_reg; public: sra(string,string,string,string); void execute(); }; class slt : public Instruction_Set { int dest_reg,reg_lhs,reg_rhs; public: slt(string,string,string,string); void execute(); }; class sltu : public Instruction_Set { int dest_reg; unsigned int reg_lhs,reg_rhs; public: sltu(string,string,string,string); void execute(); }; class slti : public Instruction_Set { int dest_reg,reg_lhs,value; public: slti(string,string,string,string); void execute(); }; class sltiu : public Instruction_Set { int dest_reg; unsigned int reg_lhs,value; public: sltiu(string,string,string,string); void execute(); }; class sub : public Instruction_Set { int src_reg1,src_reg2,dest_reg; public: sub(string,string,string,string); void execute(); }; class subu : public Instruction_Set { int src_reg1,src_reg2,dest_reg; public: subu(string,string,string,string); void execute(); }; class subi : public Instruction_Set { int src_reg,value,dest_reg; public: subi(string,string,string,string); void execute(); }; class _xor : public Instruction_Set { int src_reg1,src_reg2,dest_reg; public: _xor(string,string,string,string); void execute(); }; class _xori : public Instruction_Set { int src_reg,value,dest_reg; public: _xori(string,string,string,string); void execute(); }; class noop : public Instruction_Set { public: noop(string); void execute(); }; #endif
digaru19/MIPS_Emulator
src/datapath_elements.h
<reponame>digaru19/MIPS_Emulator #include <vector> #include <string> #include "instructions.h" #include <string.h> #ifndef MIPS_EMULATOR_H #define MIPS_EMULATOR_H using namespace std; int get_reg_no(string); class Instruction_Set; class Registers { // There are 34 registers, instead of 32, for strogin the values of HI and LO. // But, in a typical MIPS architecture, there are only 32 registers. // For the implementation of this emulator, I have considered the HI and LO registers // to be a part of the 32 general purpose registers of MIPS. // HI = 32 ; LO = 33 int Register[34]; public: Registers(); int read_reg(int); void write_reg(int ,int ); }; class Main_Memory { int Memory[400]; public: Main_Memory(); int read_mem(int); void write_mem(int,int); }; class _Instruction_Memory { vector < Instruction_Set * > instructions; int PC; int size; public: _Instruction_Memory(); void display_instr(); bool execute_next(); void update_PC(int step=1); void add_instruction(string); void execute_all(); int get_PC(); bool PC_is_valid(); }; extern Registers RegisterFile; extern Main_Memory DataMemory; extern _Instruction_Memory InstructionMemory; #endif
patil215/v8
src/ia32/frame-constants-ia32.h
<filename>src/ia32/frame-constants-ia32.h // Copyright 2012 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef V8_IA32_FRAME_CONSTANTS_IA32_H_ #define V8_IA32_FRAME_CONSTANTS_IA32_H_ #include "src/base/macros.h" #include "src/frame-constants.h" namespace v8 { namespace internal { class EntryFrameConstants : public AllStatic { public: // This is the offset to where JSEntry pushes the current value of // Isolate::c_entry_fp onto the stack. static constexpr int kCallerFPOffset = -6 * kSystemPointerSize; // EntryFrame is used by JSEntry, JSConstructEntry and JSRunMicrotasksEntry. // All of them take |root_register_value| as the first parameter. static constexpr int kRootRegisterValueOffset = +2 * kSystemPointerSize; // Rest of parameters passed to JSEntry and JSConstructEntry. static constexpr int kNewTargetArgOffset = +3 * kSystemPointerSize; static constexpr int kFunctionArgOffset = +4 * kSystemPointerSize; static constexpr int kReceiverArgOffset = +5 * kSystemPointerSize; static constexpr int kArgcOffset = +6 * kSystemPointerSize; static constexpr int kArgvOffset = +7 * kSystemPointerSize; // Rest of parameters passed to JSRunMicrotasksEntry. static constexpr int kMicrotaskQueueArgOffset = +3 * kSystemPointerSize; }; class ExitFrameConstants : public TypedFrameConstants { public: static constexpr int kSPOffset = TYPED_FRAME_PUSHED_VALUE_OFFSET(0); static constexpr int kCodeOffset = TYPED_FRAME_PUSHED_VALUE_OFFSET(1); DEFINE_TYPED_FRAME_SIZES(2); static constexpr int kCallerFPOffset = 0 * kSystemPointerSize; static constexpr int kCallerPCOffset = +1 * kSystemPointerSize; // FP-relative displacement of the caller's SP. It points just // below the saved PC. static constexpr int kCallerSPDisplacement = +2 * kSystemPointerSize; static constexpr int kConstantPoolOffset = 0; // Not used }; class WasmCompileLazyFrameConstants : public TypedFrameConstants { public: static constexpr int kNumberOfSavedGpParamRegs = 4; static constexpr int kNumberOfSavedFpParamRegs = 6; // FP-relative. static constexpr int kWasmInstanceOffset = TYPED_FRAME_PUSHED_VALUE_OFFSET(0); static constexpr int kFixedFrameSizeFromFp = TypedFrameConstants::kFixedFrameSizeFromFp + kNumberOfSavedGpParamRegs * kSystemPointerSize + kNumberOfSavedFpParamRegs * kSimd128Size; }; class JavaScriptFrameConstants : public AllStatic { public: // FP-relative. static constexpr int kLocal0Offset = StandardFrameConstants::kExpressionsOffset; static constexpr int kLastParameterOffset = +2 * kSystemPointerSize; static constexpr int kFunctionOffset = StandardFrameConstants::kFunctionOffset; // Caller SP-relative. static constexpr int kParam0Offset = -2 * kSystemPointerSize; static constexpr int kReceiverOffset = -1 * kSystemPointerSize; }; } // namespace internal } // namespace v8 #endif // V8_IA32_FRAME_CONSTANTS_IA32_H_