id
int64 0
877k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
66
| repo_stars
int64 94
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 11
values | repo_extraction_date
stringclasses 197
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1,540,538
|
SubStateSettingMyDecompositionState.cpp
|
switchboy_IsoRTS/IsoRTS/scr/Actors/SubStateSettingMyDecompositionState.cpp
|
#include "SubStateSettingMyDecompositionState.h"
#include "actor.h"
#include <iostream>
bool SubStateSettingMyDecompositionState::doAction(Actor* actor) {
// Implementation for SubStateSettingMyDecompositionState state
std::cout << "State: SubStateSettingMyDecompositionState!\n";
return false;
}
| 310
|
C++
|
.cpp
| 8
| 36.125
| 67
| 0.810631
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,539
|
SubStateWalkingToAction.cpp
|
switchboy_IsoRTS/IsoRTS/scr/Actors/SubStateWalkingToAction.cpp
|
#include "SubStateWalkingToAction.h"
#include "actor.h"
#include "../gamestate.h"
#include <iostream>
bool SubStateWalkingToAction::doAction(Actor* actor) {
if (currentGame.elapsedTimeMS - actor->_timeLastUpdate > 500) {
return true;
}
return false;
}
| 273
|
C++
|
.cpp
| 10
| 24.2
| 67
| 0.725191
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,540
|
globalfunctions.h
|
switchboy_IsoRTS/IsoRTS/scr/globalfunctions.h
|
#ifndef GLOBALFUNCTIONS_H
#define GLOBALFUNCTIONS_H
#include <list>
#include <iostream>
#include <algorithm>
#include <vector>
#include <random>
#include"SFML/Graphics.hpp"
#include "humanReadableNames.h"
#include <SFML/Network.hpp>
#include <iostream>
#include <string>
#include "server.h"
const int MAP_WIDTH = 256;
const int MAP_HEIGHT = 256;
const int mainWindowWidth = 1920;
const int mainWindowHeigth = 1080;
const int halfOfMainWindowWidth = mainWindowWidth / 2;
const int halfOfMainWindowHeigth = mainWindowHeigth / 2;
const int visableWorldHeight = static_cast<int>(mainWindowHeigth * 0.77);
const int toolbarHeight = static_cast<int>(mainWindowHeigth * 0.03);
const int visableHalfOfMainWindowWidth = static_cast<int>((mainWindowWidth * 0.8) / 2);
extern int mapOffsetX;
extern int mapOffsetY;
extern int AIPlayers;
struct cords {
int x;
int y;
bool operator==(const cords& other) const {
return x == other.x && y == other.y;
}
};
struct footprintOfBuilding
{
int amountOfXFootprint;
int amountOfYFootprint;
};
struct actorOrBuildingPrice
{
int food;
int wood;
int stone;
int gold;
int productionPoints;
};
struct command {
int timeCommandGiven;
int playerId;
int subjectId;
bool placingBuilding;
bool isStackedCommand;
cords commandCords;
worldObject subjectType;
stackOrderTypes orderType;
actionTypes actionToPerform;
};
cords toWorldMousePosition(int mouseX, int mouseY);
int roll(int min, int max);
bool rectCord (const cords& lhs, const cords& rhs);
bool compareCord(const cords& lhs, const cords& rhs);
bool sortCordByX(const cords& lhs, const cords& rhs);
cords findResource(resourceTypes kind, int unitId);
cords worldSpace(cords location);
cords miniMapSpace(cords location);
std::list<cords> getListOfCordsInCircle(int startX, int startY, int r);
std::list<cords> bresenham(cords first, cords second);
double dist(double x1, double y1, double x2, double y2);
double distEuclidean(double x1, double y1, double x2, double y2);
cords toWorldMousePosition(int mouseX, int mouseY);
void setViewports();
extern int multiplayerPlayerId;
extern int multiplayerPlayers;
enum dataType {
Text,
UserList,
MessageStatus,
Ping,
playerReady,
startGame,
giveUserId,
mapObjectBlob,
objectsBlob,
actorsBlob,
buildingsBlob,
playersBlob,
gameTimePacket,
readyForGameStartPacket,
commandPacket,
holdGame
};
const sf::Color networkTeamColors[] =
{
{0, 0, 255},
{0, 255, 0},
{255, 0, 0},
{255, 255, 0},
{0, 255, 255},
{255, 0, 255},
{255, 127, 0},
{127, 127, 127}
};
struct connectedPlayers {
sf::TcpSocket* playerSocket;
std::string name;
sf::IpAddress remoteIp;
sf::Int32 lastPing;
sf::Int32 lastPingPacketSend;
bool isReady;
bool fullyLoaded;
};
struct playersClient {
std::string name;
sf::Int32 lastPing;
bool isReady;
};
extern sf::Thread serverThread;
namespace networkStuff {
extern int port;
}
extern sf::Image cheatTile;
#endif // GLOBALFUNCTIONS_H
| 2,988
|
C++
|
.h
| 121
| 22.61157
| 87
| 0.772041
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,541
|
randomMapGenerator.h
|
switchboy_IsoRTS/IsoRTS/scr/randomMapGenerator.h
|
#pragma once
#include "globalfunctions.h"
struct foodLocationData
{
int id;
int foodGroupId;
cords foodCords;
};
extern void generateRandomMap(int players, int amountOfFoodGroups, int amountOfStoneGroups, int amountOfGoldGroups, int treeDensityLevel, int tries);
extern void centerViewOnVillager();
extern void smoothTerrain();
| 336
|
C++
|
.h
| 11
| 29.181818
| 149
| 0.830247
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,543
|
button.h
|
switchboy_IsoRTS/IsoRTS/scr/button.h
|
#ifndef BUTTON_H
#define BUTTON_H
#include "humanReadableNames.h"
class button
{
public:
button(int positionX, int positionY, spriteTypes spriteId, actionTypes actionType, int actorOrBuildingId, int buttonId, int taskId);
virtual ~button();
bool isClicked(sf::Vector2i mousePosition);
bool isHovered(sf::Vector2i mousePosition) const;
void drawButton() const;
void performAction();
void showToolTip() const;
private:
int actorOrBuildingId;
int buttonId;
int positionX;
int positionY;
int realPositionX;
int realPositionY;
int taskId;
actionTypes actionType;
spriteTypes spriteId;
};
namespace buttons {
extern bool requirementForButtonIsMet(actionTypes actionType, int unitOrBuildingId, int playerId);
}
extern std::list<button> listOfButtons;
#endif // BUTTON_H
| 843
|
C++
|
.h
| 29
| 25.310345
| 136
| 0.763682
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,544
|
main.h
|
switchboy_IsoRTS/IsoRTS/scr/main.h
|
#ifndef MAIN_H_INCLUDED
#define MAIN_H_INCLUDED
#include "globalfunctions.h"
sf::RenderWindow window(sf::VideoMode(static_cast<unsigned int>(mainWindowWidth), static_cast<unsigned int>(mainWindowHeigth)), "Isometric Demo");
sf::View totalView(sf::FloatRect(0.f, 0.f, static_cast<float>(mainWindowWidth), static_cast<float>(mainWindowHeigth)));
sf::View worldView(sf::FloatRect(0.f, 0.03f, static_cast<float>(mainWindowWidth), static_cast<float>(mainWindowHeigth)*0.77f));
sf::View topBar(sf::FloatRect(0.f, 0.f, static_cast<float>(mainWindowWidth), static_cast<float>(mainWindowHeigth)*0.03f));
sf::View toolBar(sf::FloatRect(0.f, 0.f, static_cast<float>(mainWindowWidth), static_cast<float>(mainWindowHeigth)*0.2f));
sf::View miniMap(sf::FloatRect(0.f, 0.f, static_cast<float>(mainWindowWidth)*0.2f, static_cast<float>(mainWindowHeigth)*0.2f));
int viewOffsetX = (MAP_WIDTH*64)/2;
int viewOffsetY = (MAP_HEIGHT*32)/2;
int mapOffsetX = (MAP_WIDTH/2);
int mapOffsetY = 0;
sf::RenderTexture minimapTexture;
bool minimapTextureExist = false;
#endif // MAIN_H_INCLUDED
| 1,075
|
C++
|
.h
| 16
| 65.5625
| 146
| 0.769304
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,545
|
gamestate.h
|
switchboy_IsoRTS/IsoRTS/scr/gamestate.h
|
#ifndef GAMESTATE_H
#define GAMESTATE_H
#include <list>
#include <set>
#include <array>
#include <sstream>
#include <SFML/Graphics.hpp>
#include "button.h"
#include "globalfunctions.h"
#include "humanReadableNames.h"
#include "templateBuildings.h"
#include "actorTemplates.h"
#include "collision.h"
struct adjacentTile
{
int tileId;
cords tileCords;
cords goal;
bool occupied;
int actorId;
};
extern sf::RenderWindow window;
extern sf::View totalView;
extern sf::View topBar;
extern sf::View worldView;
extern sf::View toolBar;
extern sf::View miniMap;
extern int viewOffsetX;
extern int viewOffsetY;
extern sf::RenderTexture minimapTexture;
extern bool noNewBuildings;
extern bool minimapTextureExist;
extern std::list<button> listOfButtons;
extern sf::Texture splashScreenTexture;
extern sf::Sprite splashScreenSprite;
class gameState
{
public:
bool buildingIsSelected(int id) const;
bool clickToAttack() const;
bool clickToBuildOrRepairBuilding() const;
bool clickToGatherResource() const;
bool clickToMove(cords pos, bool minimap) const;
bool isInSelectedActors(int id) const;
bool isPassable(cords location) const;
bool isPassableButMightHaveActor(cords location) const;
void calculateRectangle();
void changeBuildingType();
void changeObjectType();
void changeTiles();
void changeViewFromMiniMap() const;
void clickToGiveCommand();
void clickToGiveMinimapCommand();
void clickToPlaceActor() const;
void clickToPlaceBuilding();
void clickToPlaceObject() const;
void clickToSelect();
void clickToSelectObjectOrBuilding();
void clickUIButton() const;
void createFogOfWar();
void createVillagerButtons(int startX, int startY, int incrementalXOffset, bool& villagerButtonsAreThere);
void commandExcecutor(std::vector<command> commandsToBeExcecuted);
void drawActorBigSprite(int actorId);
void drawActorStats(int actorId, int textStartX, int textStartY);
void drawActorTitle(int actorId, int textStartX, int textStartY);
void drawActorToolbar(int spriteYOffset, int tempY, int offSetTonextCard);
void addActorSelectorButton(int i, int actorId, int startDeck, int tempY, int startY, int offSetToNextCard);
void drawBuildingBigSprite(int buildingId);
void drawBuildingConstructionToolbar(int startY);
void drawBuildingTaskToolbar(int startY);
void drawBuildingToolbar(int spriteYOffset, int tempY, int offSetTonextCard);
void drawBuildingToolbarStats(int textStartX, int textStartY);
void drawBuildingToolbarTitle(int textStartX, int textStartY);
void drawGame();
void drawGround(int i, int j);
void drawMap();
void drawMouse();
void drawMiniMap();
void drawMiniMapActors(sf::RectangleShape& miniMapPixel);
void drawMiniMapBackground(sf::RectangleShape& miniMapPixel);
void drawMiniMapMist(sf::RectangleShape& miniMapPixel);
void drawMiniMapObjects(sf::RectangleShape& miniMapPixel);
void drawMouseBox();
void drawMouseInteraction();
void drawMousePosition(int x, int y, bool noProblem);
void drawObjectToolbar(int spriteYOffset, int tempY, int offSetTonextCard);
void drawPaths();
void drawProgressBar(float pointsGained, float pointsRequired, int totalBarLength, int startBarX, int startBarY);
void drawThingsOnTile(int i, int j);
void drawToolbar();
void drawToolTip();
void drawTopBar();
void edgeScrolling() const;
void getDefinitiveSelection();
void interact();
void loadFonts();
void loadGame();
void loadMap();
void loadTextures();
void mouseLeftClick();
void mouseRightClick();
void orderRallyPoint() const;
void selectUnit(int id);
void setObjectsHaveChanged();
cords getFirstWallClick() const;
cords getNextCord(cords pos);
int getTime() const;
int getPlayerCount() const;
void setBuildingType(int id);
void setDefaultValues();
void setIsPlacingBuilding();
void setAttackMove();
void setToolbarSubMenu(int subMenu);
std::list<cords> listOfFlagsToDraw;
int elapsedTimeMS;
int buildingSelectedId;
int objectSelectedId;
int lastActor = 0;
int lastBuilding = 0;
int lastPath = 0;
int lastProjectile = 0;
int nextCommandWindow = 200;
int nextUpdateTick = 100;
int nextAITick = 500;
sf::Font font;
sf::Text text;
sf::Sprite spriteSelectedTile,spriteSelectedTileForPath, spriteEmptyTile, spriteBigSelectedIcon, spriteCommandCursor, spriteMouseCord,
spriteTileObstructed, spriteArrow, spriteFlag, spriteUIButton, spriteUnitSelectedTile, spriteTotalBackground, spriteMousePointer;
sf::Texture groundTextureSheet, textureSelectedTile, textureSelectedTileForPath, textureEmptyTile, textureBigSelectedIcon, textureCommandCursor, textureMouseCord,
textureCheatTile, textureTileObstructed, textureArrow, textureFlag, textureUIButton, textureUnitSelectedTile, textureTotalBackground, textureMousePointer;
sf::RectangleShape selectionRectangle;
sf::RectangleShape healthBarBackground;
sf::RectangleShape healthBarGreenBar;
std::array<std::array<int, MAP_HEIGHT>, MAP_WIDTH> buildingLocationList;
std::array<std::array<int, MAP_HEIGHT>, MAP_WIDTH> currentMap;
std::array<std::array<int, MAP_HEIGHT>, MAP_WIDTH> tileBitmask;
std::array<std::array<int, MAP_HEIGHT>, MAP_WIDTH> objectLocationList;
std::array<std::array<int, MAP_HEIGHT>, MAP_WIDTH> occupiedByBuildingList;
std::array<std::array<std::vector<int>, MAP_HEIGHT>, MAP_WIDTH> occupiedByActorList;
std::array<std::array<int, MAP_HEIGHT>, MAP_WIDTH> visability;
bool showPaths;
private:
bool addSubstractX;
bool addSubstractY;
bool equalIsPressed;
bool firstRound;
bool focus;
bool fogOfWarDrawnOnce = false;
bool isPlacingBuilding;
bool isPressedA;
bool isPressedB;
bool isPressedO;
bool attackMove;
bool isPressedS;
bool isPressedShift;
bool isPressedTab;
bool miniMapBackGroundDrawn = false;
bool mousePressedLeft;
bool mousePressedRight;
bool mousePressOutofWorld;
bool noFogOfWar;
bool objectsChanged = true;
bool roundDone;
int lastFogOfWarUpdated = -750;
int lastMistDraw = -500;
int lastMiniMapRefresh = -1000;
float miniMapHeigth;
float miniMapWidth;
float topBarHeigth;
float viewBoxX;
float viewBoxY;
int buildingTypeSelected;
int lastIandJ[2];
int lastFogOfWarMinimapSectorUpdated = 0;
int mapPixelHeigth;
int mapPixelWidth;
int objectTypeSelected;
int players;
int startLocation[2];
int startMouseCords[2];
int toolBarWidth;
int showToolbarSubMenu = 0;
cords firstWallClick = { -1,-1 };
cords mouseWorldPosition;
sf::Event event;
std::vector<int> selectedUnits;
std::vector<cords> rectangleCords;
sf::Vector2i mouseFakePosition;
sf::Vector2f mousePosition;
//precalculate toolbar values Note: not orderd alphabethicly because some values are needed in other calculations
const int preCalcStartX = static_cast<int>(round(mainWindowWidth / 60.f));
const int preCalcStartY = static_cast<int>(round(mainWindowHeigth / 30.f));
const int iconStartY = static_cast<int>(round(preCalcStartY + static_cast<float>(mainWindowHeigth / 27.f)));
const int preCalcCardDeckSize = static_cast<int>(round(mainWindowWidth / 1.82f));
const int preCalcIncrementalXOffset = static_cast<int>(round(64.f + (mainWindowWidth / 160.f)));
const int preCalcincrementalYOffset = static_cast<int>(round(64.f + (mainWindowHeigth / 90.f)));
const int preCalcStartDeck = static_cast<int>(round(mainWindowWidth / 4.2f));
const int preCalcStartProgress = static_cast<int>(round(mainWindowWidth / 2.48f));
const int iconStartX = static_cast<int>(round(preCalcStartDeck + static_cast<float>(mainWindowWidth / 30.f)));
const int iconBarStartX = static_cast<int>(round(iconStartX + mainWindowWidth / 6.25f));
const int startBarX = static_cast<int>(round(iconStartX + static_cast<float>(mainWindowWidth / 5.0f)));
const int startBarY = static_cast<int>(round(iconStartY + static_cast<float>(mainWindowHeigth / 46.9f)));
const int totalBarLength = static_cast<int>(round(static_cast<float>(mainWindowWidth / 6.4f)));
const int spaceBetweenFogOfWarSectorsOnXAxis = MAP_WIDTH / 4;
const int spaceBetweenFogOfWarSectorsOnYAxis = MAP_HEIGHT / 4;
};
extern gameState currentGame;
#endif // GAMESTATE_H
| 8,530
|
C++
|
.h
| 208
| 36.610577
| 167
| 0.758974
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,546
|
orderCursor.h
|
switchboy_IsoRTS/IsoRTS/scr/orderCursor.h
|
#pragma once
#include <SFML/Graphics.hpp>
#include <vector>
class orderCursor
{
public:
orderCursor(const sf::Vector2f& clickCords);
void drawCursor();
bool isFinished() const;
private:
sf::Vector2f locationOfClick;
int timeLastFrameUpdate;
bool finished;
int xOffSet;
};
extern std::vector<orderCursor> listOfOrderCursors;
| 334
|
C++
|
.h
| 16
| 19.25
| 51
| 0.812698
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,547
|
mainMenu.h
|
switchboy_IsoRTS/IsoRTS/scr/mainMenu.h
|
#pragma once
#include <string>
#include <vector>
#include "SFML/Graphics.hpp"
#include <iostream>
enum menuItemNames
{
newGame,
loadGame,
multiplayerGame,
sandBoxGame,
skirmishGame,
oneAIPlayers,
twoAIPlayers,
threeAIPlayers,
fourAIPlayers,
fiveAIPlayers,
sixAIPlayers,
sevenAIPlayers,
showCredits,
showTechTree,
rootMenu,
exitGame,
nothingSelected
};
struct menuItem {
menuItemNames id;
std::string name;
int menuLevel;
};
class menu
{
public:
menu() {
if (textureMousePointer.loadFromFile("textures/mouseHints.png"))
{
spriteMousePointer.setTexture(textureMousePointer);
spriteMousePointer.setTextureRect(sf::IntRect(0, 0, 32, 32));
}
else
{
std::cout << "Error loading texture: mouseHints.png \n" << std::endl;
}
if (menuButtonTexture.loadFromFile("textures/menuButton.png"))
{
menuButtonSprite.setTexture(menuButtonTexture);
menuButtonSprite.setTextureRect(sf::IntRect(0, 0, 900, 130));
}
else
{
std::cout << "Error loading texture: menuButton.png \n" << std::endl;
}
};
void addMenuItem(menuItemNames id, std::string name, int menuLevel);
void displayMenu();
void interactMenu();
int getMenuLevel();
void setMenuLevel(int level);
void preformMenuAction(menuItemNames itemClicked);
void doNetworking();
private:
std::vector<menuItem> menuItems;
int menuLevel = 0;
sf::Vector2f mousePosition;
sf::Sprite spriteMousePointer, menuButtonSprite;
sf::Texture textureMousePointer, menuButtonTexture;
bool focus;
bool mouseLeftPressed = false;
menuItemNames itemSelected = nothingSelected;
};
extern void createMainMenuItems(menu& mainMenu);
| 1,624
|
C++
|
.h
| 71
| 20.661972
| 72
| 0.782018
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,548
|
objectTemplates.h
|
switchboy_IsoRTS/IsoRTS/scr/objectTemplates.h
|
#pragma once
#include "globalfunctions.h"
#include "humanReadableNames.h"
#include "objects.h"
#include <SFML/Graphics.hpp>
#include "collision.h"
class objectTemplates
{
public:
objectTemplates(
objectTypes objectId,
resourceTypes typeOfResource,
int startAmountOfResources,
std::string realName,
cords spriteOrigin,
cords textureRect,
std::string texture,
int objectBigSpriteYOffset
);
objectTypes getObjectId() const;
resourceTypes getTypeOfResource() const;
int getStartAmountOfResources() const;
std::string getRealName() const;
cords getSpriteOrigin() const;
cords getTextureRect() const;
sf::Sprite& getSprite();
int getObjectBigSpriteYOffset() const;
sf::Texture getTexture();
void setTexture();
void setPosition(cords position);
private:
objectTypes objectId;
resourceTypes typeOfResource;
int startAmountOfResources;
std::string realName;
cords spriteOrigin;
cords textureRect;
sf::Sprite sprite;
sf::Texture texture;
int objectBigSpriteYOffset;
};
extern void loadObjects();
extern std::vector<objectTemplates> listOfObjectTemplates;
| 1,632
|
C++
|
.h
| 43
| 33.27907
| 62
| 0.537587
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,549
|
simpleAI.h
|
switchboy_IsoRTS/IsoRTS/scr/simpleAI.h
|
#ifndef simpleAI_H
#define simpleAI_H
#include "globalfunctions.h"
class simpleAI
{
public:
simpleAI(int playerId, int difficultyLevel);
void update();
private:
bool hasBuildingType(int id);
void attakCommandUnit(int unitId, cords targetCords, bool first);
void buildBuilding(int buildingId, cords buildingCords);
void buildBuildingNearUnlessBuilding(int buildingId, int idleVillagerId, resourceTypes nearResource);
void excecuteAttackPlan();
void buildCommandUnit(int unitId, cords targetCords);
void distributeIdleVillagers();
void gatherCommandUnit(int unitId, cords targetCords);
void moveCommandUnit(int unitId, cords targetCords);
void produceCommandBuilding(int buildingId, bool isResearch, int idOfUnitOrResearch);
void sandboxScript();
void orderBuildingToProduceUnitIfItHadNoTask(int buildingTypeId, int unitId);
bool buildDropOffPointWhen(int buildingId, resourceTypes resource, int first, int second, int third);
void tryBuilding();
int isBuildingThereButIncomplete(int type);
std::vector<int> getBuildingIdsOfType(int type);
cords getFreeBuildingSlot(int buildingId, cords closeToThis); //Just a random slot
cords getOptimalFreeBuildingSlot(int buildingId, cords closeToVillager, bool closeToWood, bool closeToFood, bool closeToStone, bool closeToGold); //Best possible slot
int attackWaveSent = 0;
int stoneMiningCampOwned;
int playerId;
int difficultyLevel;
};
extern std::vector<simpleAI> listOfAI;
extern cords findResource(resourceTypes kind, int unitId);
#endif
| 1,585
|
C++
|
.h
| 35
| 43.342857
| 170
| 0.793014
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,550
|
connection.h
|
switchboy_IsoRTS/IsoRTS/scr/connection.h
|
#pragma once
#include "globalfunctions.h"
class connection
{
public:
connection() {};
bool connect(sf::IpAddress hostIp, int remotePort, std::string playerName);
sf::TcpSocket* getTcpSocket();
bool reconnect();
void disconnect();
bool isConnected();
std::string getPlayerName();
private:
sf::TcpSocket tcpSocket;
std::string playerName;
sf::IpAddress hostIp;
int remotePort = 0;
bool connected;
};
extern connection currentConnection;
| 457
|
C++
|
.h
| 20
| 21.05
| 76
| 0.771363
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,551
|
actorTemplates.h
|
switchboy_IsoRTS/IsoRTS/scr/actorTemplates.h
|
#pragma once
#include "globalfunctions.h"
#include <vector>
#include <SFML/Graphics.hpp>
#include "collision.h"
#include "humanReadableNames.h"
enum class actorNames : uint32_t {
villager,
swordsman
};
struct actorButtonVariables {
spriteTypes sprite;
actionTypes action;
int subMenu;
};
class actorTemplates
{
public:
actorTemplates(
actorNames actorId,
bool doesRangedDamage,
int timeBetweenShots,
int timeToCrossOneTile,
int hitPoints,
int meleeDamage,
int projectileType,
int range,
int rangedDamage,
int rateOfFire,
int splashDamage,
cords textureRect,
actorOrBuildingPrice priceOfActor,
std::string actorTexture,
std::string realActorName,
cords spriteOrigin,
int bigSpriteYOffset,
std::vector<actorButtonVariables> actorButtons
);
//getters
actorNames getActorId() const;
int getBigSpriteYOffset() const;
bool getDoesRangedDamage() const;
int getTimeBetweenShots() const;
int getTimeToCrossOneTile() const;
int getHitPoints() const;
int getMeleeDamage() const;
int getProjectileType() const;
int getRange() const;
int getRangedDamage() const;
int getRateOfFire() const;
int getSplashDamage() const;
cords getTextureRect() const;
actorOrBuildingPrice getPriceOfActor() const;
sf::Sprite& getActorSprite();
sf::Texture getActorTexture();
std::string getRealActorName() const;
std::list<actorButtonVariables> getActorButtonsOfMenu(int menu);
//setters
void setActorTexture();
void setSpritePosition(cords position);
private:
actorNames actorId;
int bigSpriteYOffset;
bool doesRangedDamage;
int timeBetweenShots;
int timeToCrossOneTile;
int hitPoints;
int meleeDamage;
int projectileType;
int range;
int rangedDamage;
int rateOfFire;
int splashDamage;
cords spriteOrigin;
cords textureRect;
actorOrBuildingPrice priceOfActor;
sf::Sprite actorSprite;
sf::Texture actorTexture;
std::string realActorName;
std::vector<actorButtonVariables> actorButtons;
};
extern std::vector<actorTemplates> listOfActorTemplates;
extern void loadActors();
| 3,578
|
C++
|
.h
| 83
| 37.951807
| 70
| 0.454389
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,552
|
gametext.h
|
switchboy_IsoRTS/IsoRTS/scr/gametext.h
|
#ifndef GAMETEXT_H
#define GAMETEXT_H
#include <list>
#include <string>
struct gameMessage
{
std::string message;
int color;
int timeAdded;
};
class gametext
{
public:
void addDebugMessage(std::string message, int color);
void addNewMessage(std::string message, int color);
void drawDebugMessages() const;
void drawMessages() const;
void throwOutOldMessages();
private:
std::list<gameMessage> listOfMessages;
std::list<gameMessage> debugMessages;
};
extern gametext gameText;
#endif // GAMETEXT_H
| 542
|
C++
|
.h
| 24
| 19.708333
| 57
| 0.752437
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,554
|
player.h
|
switchboy_IsoRTS/IsoRTS/scr/player.h
|
#ifndef PLAYER_H
#define PLAYER_H
#include <vector>
#include "humanReadableNames.h"
struct playerStats
{
int amountOfWood;
int amountOfFood;
int amountOfGold;
int amountOfStone;
int currentPopulation;
int populationRoom;
int team;
};
class player
{
public:
player();
virtual ~player();
void addResources(resourceTypes resource, int amount);
void substractResources(resourceTypes resource, int amount);
void addToCurrentPopulation(int amount);
void substractFromCurrentPopulation(int amount);
void addToPopulationRoom(int amount);
void substractFromPopulationRoom(int amount);
void setTeamToNeutral(int team);
void setTeamToAlly(int team);
void setTeamToEnemy(int team);
void syncPlayer(int food, int wood, int stone, int gold, bool isDefeated);
int getFriendOrFoo(int team);
int getTeam() const;
void setTeam(int team);
bool isPlayerDefeated() const;
void clearLists();
void insertIdIntoIdleVillagerList(int id);
void insertVillagerList(int id);
void insertGatheringWood(int id);
void insertGatheringFood(int id);
void insertGatheringStone(int id);
void insertGatheringGold(int id);
void insertBuilding(int id);
void insertUnit(int id);
int getPopulationRoom() const;
int getIdleVillagerId(int it) const;
int getIdleVillagers() const;
int getVillagers() const;
int getTotalGatheringWood() const;
int getTotalGatheringFood() const;
int getTotalGatheringStone() const;
int getTotalGatheringGold() const;
int getGatheringWood(int id) const;
int getGatheringFood(int id) const;
int getGatheringStone(int id) const;
int getGatheringGold(int id) const;
int getTotalGathering(resourceTypes it) const;
int getTotalBuilding() const;
int getBuilder(int id) const;
int getVillager(int id) const;
int getSwordsman(int id) const;
int getTotalSwordsman() const;
int getTotalUnits() const;
int getUnit(int id) const;
void insertSwordsman(int id);
playerStats getStats() const;
private:
int team;
int amountOfWood;
int amountOfFood;
int amountOfGold;
int amountOfStone;
int currentPopulation;
int populationRoom;
int friendOrFoo[8];
bool isDefeated;
bool isParticipating;
std::vector<int> building;
std::vector<int> gatheringFood;
std::vector<int> gatheringGold;
std::vector<int> gatheringStone;
std::vector<int> gatheringWood;
std::vector<int> idleVillagersList;
std::vector<int> listOfSwordsman;
std::vector<int> villagersList;
std::vector<int> units;
};
extern int currentPlayerI;
extern player listOfPlayers[8];
#endif // PLAYER_H
| 2,739
|
C++
|
.h
| 88
| 26.738636
| 78
| 0.734216
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,555
|
humanReadableNames.h
|
switchboy_IsoRTS/IsoRTS/scr/humanReadableNames.h
|
#ifndef HUMANREADABLENAMES_H
#define HUMANREADABLENAMES_H
enum class resourceTypes
{
resourceWood,
resourceFood,
resourceStone,
resourceGold,
All,
None
};
enum class objectTypes : uint32_t
{
cactus,
cypress,
maple,
pine,
stone,
gold,
berry
};
enum class spriteTypes
{
spriteTownCenter,
spriteHouse,
spriteVillager,
spriteCancel,
spriteMill,
spriteLumberCamp,
spriteBarracks,
spriteSwordsman,
spriteMiningCamp,
spriteWall,
spriteGate,
spriteOpenGate,
spriteCivilBuilding,
spriteMilitairyBuilding,
spriteGoBack,
spriteAttackMove
};
enum class actionTypes
{
actionBuildTownCenter,
actionBuildHouse,
actionUnitSelect,
actionMakeVillager,
actionCancelBuilding,
actionCancelProduction,
actionBuildMill,
actionBuildLumberCamp,
actionBuildBarracks,
actionMakeSwordsman,
actionBuildMiningCamp,
actionBuildWall,
actionMakeGate,
actionOpenGate,
actionCloseGate,
actionShowCivilBuildings,
actionShowMilitairyBuildings,
actionShowBack,
actionAttackMove,
none
};
enum class stackOrderTypes
{
stackActionMove,
stackActionGather,
stackActionBuild,
stackActionAttack,
stackActionAttackMove,
none
};
enum class worldObject {
actor,
object,
building,
none
};
#endif HUMANREADABLENAMES_H
| 1,412
|
C++
|
.h
| 79
| 13.78481
| 33
| 0.748679
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,557
|
actors.h
|
switchboy_IsoRTS/IsoRTS/scr/actors.h
|
#ifndef ACTORS_H
#define ACTORS_H
#include <cmath>
#include <list>
#include <SFML/System.hpp>
#include "gamestate.h"
#include "globalfunctions.h"
#include "actorTemplates.h"
#include "cells.h"
#include "Actors/actorStructs.h"
class Actors
{
public:
Actors(int type, cords location, int actorTeam, int actorId);
void drawActor();
void renderPath();
void update();
void buildBuilding();
void calculateRoute();
bool chaseTarget();
void cleanUp();
void clearCommandStack();
void clearRoute();
void doMeleeDamage();
void doNextStackedCommand();
void doTaskIfNotWalking();
void fightOrFlight(int idOfAttacker);
void findNearestDropOffPoint();
void findNearestSimilarResource();
void gatherResource();
void getNewBuildingTileForSameBuilding();
void handleBuilding();
void handleResourceGathering();
void houseKeeping();
void killActor();
void moveActorIfWalking();
void makeSureActorIsOnTheMap();
void printActorDebugText();
void pathAStar();
void selectAndAttackNextTarget(int range);
void retryWalkingOrChangeGoal();
void routing(std::vector<Cells>& cellsList, int endCell, int startCell, bool endReached);
void searchAltetnative();
void setCommonGoalTrue();
void setDoAttackMoveTrue();
void setGatheringRecource(bool flag);
void shootProjectile();
void stackOrder(cords Goal, stackOrderTypes orderType);
void startGatheringAnimation();
void startWalking();
void takeDamage(int amountOfDamage, int idOfAttacker);
void unloadAndReturnToGathering();
void makeSurePathIsOnListToGetCalculated();
void updateGoal(cords goal, int waitTime);
void updateGoalPath();
void walkBackToOwnSquare();
void walkToNextSquare();
void walkBackAfterAbortedCommand();
void animateWalkingToResource();
void anitmateWalkingBackAfterAbortedCommand();
//getters
bool getIsBuilding() const;
bool getHasRoute();
bool getIsIdle() const;
bool getIsAlive() const;
bool getIsGathering() const;
bool getIsInitialized() const;
int getActorId() const;
int getBuildingId() const;
int getMeleeDMG() const;
int getRangedDMG() const;
int getTeam() const;
int getType() const;
sf::IntRect getLastIntRect() const;
cords getGoal() const;
cords getEndGoal();
resourceTypes getResourceGathered() const;
cords getActorCords() const;
const std::list<cords>& getRejectedTargetsList() const;
std::pair<int, int> getHealth() const;
std::string getNameOfActor() const;
std::string getResources() const;
//setters
void setIsBuildingTrue(int buildingId, cords goal);
void setIsDoingAttack(bool chasing);
private:
bool isWalkingToMiddleOfSquare;
bool lastTile;
bool actorAlive;
bool doesRangedDamage;
bool busyWalking;
bool commonGoal;
bool isGatheringRecources;
bool isAtRecource;
bool isAtCarryCapacity;
bool hasToUnloadResource;
bool isWalkingToUnloadingPoint;
bool reachedUnloadingPoint;
bool hasUnloaded;
bool carriesRecources;
bool pathFound;
bool goalNeedsUpdate;
bool isBackAtOwnSquare;
int walkingToResource = 0;
bool noPathPossible;
bool routeNeedsPath;
bool initialized;
bool isBuilding;
bool hasMoved;
bool isMeleeAttacking;
bool isRangedAttacking;
bool isFindingAlternative;
bool isIdle;
bool realPath;
bool wasAttackMove;
cords actorCords;
cords actorGoal;
cords actorRealGoal;
cords actorCommandGoal;
cords actionPreformedOnTile;
int idOfTarget;
int actorType;
int actorTeam;
int actorHealth;
int buildingId;
int actorId;
int hitPoints;
int meleeDamage;
int rangedDamage;
int range;
resourceTypes ResourceBeingGatherd;
int amountOfGold;
int amountOfWood;
int amountOfStone;
int amountOfFood;
int orientation;
int currentFrame;
int spriteYOffset;
int retries;
int splashDamage;
int projectileType;
int waitForAmountOfFrames;
int rateOfFire;
float offSetX;
float offSetY;
int lastChaseTime = 0;
int timePassedSinceChangingOffset;
int timeStartedAction;
int timeLastOffsetChange;
int timeLastUpdate;
int timeLastPathTry;
int timeStartedWalkingToRecource;
int timeLastAttempt;
int timeBetweenShots;
int timeLastRetry;
int timeToCrossOneTile;
drawXYOverride isWalkingBackXYDrawOverride;
unfinischedWalking dataOnPositionAbortedWalk;
nearestBuildingTile dropOffTile;
std::list<cords> listOfTargetsToRejectUntilSuccesfullMovement;
std::list<routeCell> route;
std::list <nearestBuildingTile> listOfDropOffLocations;
std::list <nearestBuildingTile> listOfResourceLocations;
std::list<orderStack> listOfOrders;
sf::IntRect lastIntRect;
};
//extern std::vector<Actor> listOfActors;
//extern std::vector<int> listOfActorsWhoNeedAPath;
//extern nearestBuildingTile findNearestBuildingTile(int buildingId, int actorId);
#endif // ACTORS_H
| 5,094
|
C++
|
.h
| 170
| 25.388235
| 93
| 0.746545
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,558
|
objects.h
|
switchboy_IsoRTS/IsoRTS/scr/objects.h
|
#ifndef OBJECTS_H
#define OBJECTS_H
#include <vector>
#include <string>
#include "globalfunctions.h"
#include "humanReadableNames.h"
#include "objectTemplates.h"
#include <SFML/Graphics.hpp>
#include "Actors/actorStructs.h"
class objects
{
public:
objects(objectTypes type, cords location, int objectId);
void destroyObject();
void drawObjectFootprint(objectTypes type, cords mouseWorld) const;
void drawObject(int i, int j);
void drawObjectSprite(objectTypes spriteNumber, int i, int j) const;
void substractResource();
int amountOfResourcesLeft() const;
std::string nameOfResource() const;
sf::IntRect getLastIntRect() const;
int getObjectId() const;
cords getLocation() const;
std::string getName() const;
objectTypes getType() const;
resourceTypes getTypeOfResource() const;
bool getIsInWorld() const;
void takeDamage(const int& amountOfDamage, const int& attackerId, const targetTypes attackerType);
private:
sf::IntRect _lastIntRect;
int _objectId;
objectTypes _objectType;
cords _location;
resourceTypes _typeOfResource;
int _resourceLeft;
bool _isInWorld;
int _health = 250;
int _maxHealth = 250;
};
extern std::vector<objects> listOfObjects;
#endif // OBJECTS_H
| 1,477
|
C++
|
.h
| 41
| 32.195122
| 113
| 0.648592
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,560
|
templateBuildings.h
|
switchboy_IsoRTS/IsoRTS/scr/templateBuildings.h
|
#pragma once
#include "globalfunctions.h"
#include <vector>
#include <SFML/Graphics.hpp>
#include "collision.h"
#include "humanReadableNames.h"
#include "button.h"
//#include "buildings.h"
enum class buildingNames : uint32_t {
house,
towncenter,
mill,
lumbercamp,
barracks,
miningcampstone,
miningcampgold,
wall
};
struct buttonVariables {
spriteTypes sprite;
actionTypes action;
};
class templateBuildings
{
public:
templateBuildings(
bool canDoRangedDamage,
bool recievesWood,
bool recievesStone,
bool recievesGold,
bool recievesFood,
buildingNames idOfBuilding,
int hitPointsTotal,
int amountOfRangedDamage,
int range,
int buildingPointsNeeded,
int supportsPopulationOf,
int offSetYStore,
int amountOfAnimationSprites,
actorOrBuildingPrice priceOfBuilding,
footprintOfBuilding buildingFootprint,
cords buildingSprite,
std::string buildingTexture,
cords origin,
std::string realBuildingName,
int bigSpriteYOffset,
bool isWall,
std::list<buttonVariables> listOfBuildingButtons
);
//Getters
bool getCanDoRangedDamage() const;
bool getRecievesWood() const;
bool getRecievesStone() const;
bool getRecievesGold() const;
bool getRecievesFood() const;
bool getIsWall() const;
buildingNames getIdOfBuilding() const;
int getHitPointsTotal() const;
int getAmountOfRangedDamage() const;
int getRange() const;
int getBuildingPointsNeeded() const;
int getSupportsPopulationOf() const;
int getOffSetYStore() const;
int getAmountOfAnimationSprites() const;
actorOrBuildingPrice getPriceOfBuilding() const;
footprintOfBuilding getBuildingFootprint() const;
sf::Sprite& getBuildingSprite();
sf::Texture getBuildingTexture();//TODO: should this return an sf::Texture& instead? - If I keep it probably, but I haven't yet foud a use for it so it might get scrapped
std::string getBuildingName() const;
int getBigSpriteYOffset() const;
void createBuildingButtons(int startX, int startY, int buildingId, int incrementalXOffset, bool& buttonsAreThere);
//setters
void setSpritePosition(cords position);
void setSpriteTexture(); //still needed since texture needs to set on sprite AFTER it is in its 'permanent' momory position (once the listOfBuildingTemplates is finished)
private:
bool canDoRangedDamage;
bool recievesWood;
bool recievesStone;
bool recievesGold;
bool recievesFood;
bool isWall;
buildingNames idOfBuilding;
int hitPointsTotal;
int amountOfRangedDamage;
int range;
int buildingPointsNeeded;
int supportsPopulationOf;
int offSetYStore;
int amountOfAnimationSprites;
cords textureRect;
cords origin;
actorOrBuildingPrice priceOfBuilding;
footprintOfBuilding buildingFootprint;
sf::Sprite buildingSprite;
sf::Texture buildingTexture;
std::string realBuildingName;
int bigSpriteYOffset;
std::list<buttonVariables> listOfBuildingButtons;
};
extern std::vector<templateBuildings> listOfBuildingTemplates;
extern void loadBuildings();
| 4,289
|
C++
|
.h
| 101
| 38.108911
| 193
| 0.55715
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,561
|
projectile.h
|
switchboy_IsoRTS/IsoRTS/scr/projectile.h
|
#pragma once
#include "globalfunctions.h"
#include <vector>
class projectile
{
public:
projectile(int projectileStartX, int projectileStartY, int projectileTargetX, int projectileTargetY, int projectileType, int damageOnImpact, int splashDamageOnImpact, int firedBy, targetTypes firedByType);
void doDamage() const;//not detemenistic yet!
void doSplashDamage();
void drawProjectile();
void updatePosition();//not detemenistic yet!
void interprolatePositionForDrawCall();
int getTimeLastUpdate() const;
private:
cords _projectilePosition;
cords _projectileTarget;
int _timeFired;
int _lastInterprolation = 0;
int _projectileType;
int _damageOnImpact;
int _splashDamageOnImpact;
int _firedBy;
targetTypes _firedByType;
//not detemenistic yet!
int _X;
int _Y;
int _Z;
int _interProlateX = 0;
int _interProlateY = 0;
int _interProlateZ = 0;
int _interProlateDeltaZ = 0;
int _deltaX;
int _deltaY;
int _deltaZ;
float _projectileRotation;
bool _reachedTarget;
};
extern std::vector<projectile> listOfProjectiles;
| 1,053
|
C++
|
.h
| 38
| 25.710526
| 206
| 0.792247
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,562
|
buildings.h
|
switchboy_IsoRTS/IsoRTS/scr/buildings.h
|
#ifndef BUILDINGS_H
#define BUILDINGS_H
#include <list>
#include <string>
#include <vector>
//#include "humanReadableNames.h"
#include "gamestate.h"
#include "globalfunctions.h"
struct buildingQueue
{
bool isResearch;
int idOfUnitOrResearch;
int productionPointsGained;
int productionPointsNeeded;
int lastTimeUpdate;
};
struct orderContainer {
cords goal;
stackOrderTypes orderType;
bool isSet;
};
class buildings
{
public:
buildings() {
this->exists = false;
this->buildingType = 0;
this->startLocation = { 0, 0};
this->endLocation = { 0, 0 };
this->buildingId = 0;
this->ownedByPlayer = -1;
this->buildingCompleted = false;
this->exists = true;
this->lastShotFired = 0;
this->rallyPoint = { {0,0}, stackOrderTypes::stackActionMove, false }; //set dummy values for the rally point
this->lastFrameUpdate = 0;
hitPointsTotal = 0;
hitPointsLeft = 0;
canDoRangedDamage = false;
amountOfRangedDamage = 0;
range = 0;
recievesWood = false;
recievesStone = false;
recievesGold = false;
recievesFood = false;
this->hasDisplayedError = false;
buildingPointsNeeded = 0;
buildingPointsRecieved = 0;
supportsPopulationOf = 0;
this->offSetYStore = 0;
this->amountOfAnimationSprites = 0;
}
buildings(int type, cords startLocation, int buildingId, int team);
bool claimFreeBuiildingTile(int id, int actorId);
bool hasTask() const;
void addBuildingPoint();
void checkOnEnemyAndShoot();
void doProduction();
void drawBuilding(int i, int j, int type, bool typeOverride);
void drawBuildingFootprint(int type, cords mouseWorld);
void fillAdjacentTiles();
void getTask(bool isResearch, int idOfUnitOrResearch);
void removeActorFromBuildingTile(int actorId);
void removeBuilding();
void spawnProduce();
void takeDamage(int amountOfDamage);
void update();
int getBuildingId() const;
bool getExists() const;
bool getCompleted() const;
bool getGateIsOpen() const;
bool getIsGate() const;
cords getLocation() const;
int getRangedDMG() const;
int getTeam() const;
int getType() const;
bool canBeGate() const;
std::list<buildingQueue> getProductionQueue() const;
resourceTypes getRecievesWhichResources() const;
std::list<cords> getFootprintOfBuilding() const;
std::pair<int, int> getBuildingPoints() const;
std::pair<int, int> getHealth() const;
std::string getName() const;
std::vector<adjacentTile> getDropOffTiles() const;
std::vector<adjacentTile> getFreeBuildingTile() const;
void setCompleted();
void setIsGate();
void setGateOpen(bool state);
void setRallyPoint(cords goal, stackOrderTypes orderType);
void removeTask(int id);
private:
std::list<buildingQueue> productionQueue;
bool buildingCompleted;
bool gateIsOpen = false;
bool canDoRangedDamage;
bool exists;
bool hasDisplayedError;
bool recievesFood;
bool recievesGold;
bool recievesStone;
bool recievesWood;
bool isGate = false;
int lastFrameUpdate;
int lastShotFired;
int amountOfAnimationSprites;
int amountOfRangedDamage;
int buildingId;
int buildingPointsNeeded;
int buildingPointsRecieved;
int buildingType;
cords endLocation;
int hitPointsLeft;
int hitPointsTotal;
int offSetYStore;
int ownedByPlayer;
int range;
cords startLocation;
int supportsPopulationOf;
std::vector<adjacentTile> adjacentTiles;
orderContainer rallyPoint;
std::string buildingName;
};
extern std::vector<buildings> listOfBuildings;
extern bool noNewBuildings;
#endif // BUILDINGS_H
| 5,248
|
C++
|
.h
| 125
| 36.712
| 117
| 0.509489
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,563
|
cells.h
|
switchboy_IsoRTS/IsoRTS/scr/cells.h
|
#pragma once
#include <vector>
#include "globalfunctions.h"
struct Cells
{
public:
Cells() {
position = { 0,0 };
parentCellId = 0;
cummulativeCost = 0;
cellId = 0;
backParent = 0;
costToGoal = 0;
totalCostGuess = 0;
}
Cells(cords cellPosition, int cellId);
Cells(cords cellPosition, int cellId, bool obstacle);
cords position;
int parentCellId, cummulativeCost, cellId, backParent;
double costToGoal, totalCostGuess;
bool visited = false;
bool visitedBack = false;
bool obstacle = false;
std::vector<int> neighbours;
void addNeighbours(const std::vector<Cells>& cellsList);
};
extern std::vector<Cells> baseCellList;
extern void updateCells(int goalId, int startId, std::vector<Cells>& cellsList, bool cantPassActors);
bool canReachTarget(const cords& source, const cords& target, bool _cantPassActors);
| 911
|
C++
|
.h
| 29
| 26.724138
| 101
| 0.699659
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,564
|
commandSync.h
|
switchboy_IsoRTS/IsoRTS/scr/commandSync.h
|
#ifndef COMMANDSYNC_H
#define COMMANDSYNC_H
#include "globalfunctions.h"
#include "humanReadableNames.h"
class commandSync
{
public:
commandSync();
void addCommand(command givenCommand);
void sendNetWorkCommands();
void recieveNetworkCommands();
std::vector <command> getNextCommandsToExcecute(int gameTime);
std::vector <command> getAllCommandsGiven();
private:
std::vector<command> listOfCommands;
std::vector<command> listOfUnsentCommands;
std::vector<command> listOfAllCommandsExcecuted;
std::vector<std::vector<int>> recievedCommandBursts; //player id, timeStampOfCommandBurst
};
extern commandSync gameDirector;
#endif
| 639
|
C++
|
.h
| 21
| 28.761905
| 90
| 0.82899
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,565
|
BaseStateFighting.h
|
switchboy_IsoRTS/IsoRTS/scr/Actors/BaseStateFighting.h
|
#pragma once
#include "stateBase.h"
#include "actorStructs.h"
class BaseStateFighting : public StateBase {
public:
using StateBase::StateBase;
bool doAction(Actor* actor) override;
cords getActionPreformedOn() override;
void setActionPreformedOn(cords location) override;
ModesOfAttack getModeOfAttack() override;
private:
targetTypes getTargettype() const;
int getIdOfTarget() const;
FightOrFlight fightOrFlight(Actor* actor);
private:
ModesOfAttack _modeOfAttack;
int _idOfTarget;
targetTypes _targetType;
bool _wasAttakOrder = true;
bool _isInitialised = false;
friend class groundStateAttaking;
friend class groundStateFleeing;
friend class subStateResumePreviousTask;
friend class subStateSearchNextTarget;
friend class subStateInRangeMelee;
friend class subSateInRangeRanged;
friend class subStateSettingGoalToFleeTo;
};
| 914
|
C++
|
.h
| 28
| 28.535714
| 55
| 0.784983
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,566
|
SubStateWalkingToAction.h
|
switchboy_IsoRTS/IsoRTS/scr/Actors/SubStateWalkingToAction.h
|
#pragma once
#include "stateBase.h"
class SubStateWalkingToAction : public StateBase {
public:
using StateBase::StateBase;
bool doAction(Actor* actor) override;
};
| 172
|
C++
|
.h
| 7
| 22.428571
| 50
| 0.781818
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,567
|
GroundStateFleeing.h
|
switchboy_IsoRTS/IsoRTS/scr/Actors/GroundStateFleeing.h
|
#pragma once
#include "stateBase.h"
class GroundStateFleeing : public StateBase {
public:
using StateBase::StateBase;
bool doAction(Actor* actor) override;
};
| 170
|
C++
|
.h
| 7
| 21.714286
| 45
| 0.775
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,568
|
BaseStateWalkingAToB.h
|
switchboy_IsoRTS/IsoRTS/scr/Actors/BaseStateWalkingAToB.h
|
#pragma once
#include "stateBase.h"
class BaseStateWalkingAToB : public StateBase {
public:
using StateBase::StateBase;
bool doAction(Actor* actor) override;
};
| 169
|
C++
|
.h
| 7
| 22
| 47
| 0.777778
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,569
|
GroundStateSearchAlternativeBuildingSpot.h
|
switchboy_IsoRTS/IsoRTS/scr/Actors/GroundStateSearchAlternativeBuildingSpot.h
|
#pragma once
#include "stateBase.h"
class GroundStateSearchAlternativeBuildingSpot : public StateBase {
public:
using StateBase::StateBase;
bool doAction(Actor* actor) override;
};
| 189
|
C++
|
.h
| 7
| 24.857143
| 67
| 0.802198
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,570
|
StateNames.h
|
switchboy_IsoRTS/IsoRTS/scr/Actors/StateNames.h
|
#pragma once
enum class BaseStateNames{
NONE,
Idle,
WalikngAToB,
Gathering,
Building,
Fighting,
Dead
};
enum class GroundStateNames {
NONE,
Walking,
AtTheResource,
ReturningTheResource,
AtTheBuilding,
Attacking,
Fleeing,
Decomposing,
FindAlternativeSource,
SearchAlternativeBuildingSpot
};
enum class SubStateNames {
NONE,
WalkingToNextSquare,
SearchingAPath,
SearchingNextSimilairResource,
SearchingDropOffPoint,
SearchingAlternativeBuildingSpot,
SearchingAlternativeBuildingToBuilt,
MeleeAttacking,
RangedAttacking,
SearchNextTarget,
SettingGoalToFleeTo,
SettingMyDecompositionState,
CountingDownToDestroySelf,
WalkingToAction,
WalkingBackFromAction,
BuildingTheBuilding,
GatheringTheResource,
CanceldWhileWalking,
DroppingOffResource,
FindingNewTarget,
};
enum class ModesOfAttack {
melee,
ranged,
};
| 845
|
C++
|
.h
| 48
| 15.75
| 37
| 0.872956
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,571
|
SubStateMeleeAttacking.h
|
switchboy_IsoRTS/IsoRTS/scr/Actors/SubStateMeleeAttacking.h
|
#pragma once
#include "stateBase.h"
class SubStateMeleeAttacking : public StateBase {
public:
using StateBase::StateBase;
bool doAction(Actor* actor) override;
private:
bool checkAndMoveActorToRightOrientation(Actor* actor, cords const targetCords);
bool _isDoneWalking = false;
};
| 299
|
C++
|
.h
| 10
| 27.2
| 84
| 0.785467
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,572
|
StateCanceledWhileWalking.h
|
switchboy_IsoRTS/IsoRTS/scr/Actors/StateCanceledWhileWalking.h
|
#pragma once
#include "stateBase.h"
class StateCanceledWhileWalking : public StateBase {
public:
using StateBase::StateBase;
bool doAction(Actor* actor) override;
bool getMoved() override;
private:
bool _moved = false;;
bool _walkBackSet = false;
};
| 271
|
C++
|
.h
| 11
| 21.727273
| 52
| 0.741313
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,573
|
SubStateWalkingToNextSquare.h
|
switchboy_IsoRTS/IsoRTS/scr/Actors/SubStateWalkingToNextSquare.h
|
#pragma once
#include "stateBase.h"
class SubStateWalkingToNextSquare : public StateBase {
public:
using StateBase::StateBase;
bool doAction(Actor* actor) override;
bool getMoved() override;
private:
bool walkToNextRoutePoint(Actor* actor);
bool checkIfEnemyHasMoved(Actor* actor);
bool retryWalkingOrChangeGoal(Actor* actor);
bool _lastCellBlocked = false;
int _timeLastRetry = 0;
int _retries = 0;
bool _moved = false;
};
| 465
|
C++
|
.h
| 16
| 25.5
| 54
| 0.741071
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,574
|
GroundStateBuildingTheBuilding.h
|
switchboy_IsoRTS/IsoRTS/scr/Actors/GroundStateBuildingTheBuilding.h
|
#pragma once
#include "stateBase.h"
class GroundStateBuildingTheBuilding : public StateBase {
public:
using StateBase::StateBase;
bool doAction(Actor* actor) override;
private:
bool checkIfBuildingIsThereAndIncomplete(Actor* actor);
};
| 249
|
C++
|
.h
| 9
| 25.222222
| 59
| 0.8
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,575
|
BaseStateIdle.h
|
switchboy_IsoRTS/IsoRTS/scr/Actors/BaseStateIdle.h
|
#pragma once
#include "stateBase.h"
class BaseStateIdle : public StateBase {
public:
using StateBase::StateBase;
bool doAction(Actor* actor) override;
};
| 162
|
C++
|
.h
| 7
| 21
| 41
| 0.767742
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,576
|
SubStateFindingNewTarget.h
|
switchboy_IsoRTS/IsoRTS/scr/Actors/SubStateFindingNewTarget.h
|
#pragma once
#include "stateBase.h"
class SubStateFindingNewTarget : public StateBase {
public:
using StateBase::StateBase;
bool doAction(Actor* actor) override;
};
| 173
|
C++
|
.h
| 7
| 22.571429
| 51
| 0.783133
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,577
|
GroundStateDecomposing.h
|
switchboy_IsoRTS/IsoRTS/scr/Actors/GroundStateDecomposing.h
|
#pragma once
#include "stateBase.h"
class GroundStateDecomposing : public StateBase {
public:
using StateBase::StateBase;
bool doAction(Actor* actor) override;
};
| 171
|
C++
|
.h
| 7
| 22.285714
| 49
| 0.780488
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,578
|
GroundStateAttacking.h
|
switchboy_IsoRTS/IsoRTS/scr/Actors/GroundStateAttacking.h
|
#pragma once
#include "stateBase.h"
class GroundStateAttacking : public StateBase {
public:
using StateBase::StateBase;
bool doAction(Actor* actor) override;
};
| 169
|
C++
|
.h
| 7
| 22
| 47
| 0.777778
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,579
|
SubStateSettingGoalToFleeTo.h
|
switchboy_IsoRTS/IsoRTS/scr/Actors/SubStateSettingGoalToFleeTo.h
|
#pragma once
#include "stateBase.h"
#include "actorStructs.h"
enum class direction {
upLeft,
up,
upRight,
left,
right,
downLeft,
down,
downRight,
};
class SubStateSettingGoalToFleeTo : public StateBase {
public:
using StateBase::StateBase;
bool doAction(Actor* actor) override;
};
cords getAgressorCords(const int& agressorId, const targetTypes& agressorType);
| 403
|
C++
|
.h
| 19
| 18
| 79
| 0.740838
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,580
|
StateCanceled.h
|
switchboy_IsoRTS/IsoRTS/scr/Actors/StateCanceled.h
|
#pragma once
#include "stateBase.h"
class StateCanceled : public StateBase {
public:
using StateBase::StateBase;
bool doAction(Actor* actor) override;
};
| 162
|
C++
|
.h
| 7
| 21
| 41
| 0.767742
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,581
|
BaseStateBuilding.h
|
switchboy_IsoRTS/IsoRTS/scr/Actors/BaseStateBuilding.h
|
#pragma once
#include "stateBase.h"
class BaseStateBuilding : public StateBase {
public:
using StateBase::StateBase;
bool doAction(Actor* actor) override;
cords getActionPreformedOn() override;
void setActionPreformedOn(cords location) override;
private:
bool initiateBuilding(Actor* actor);
cords _originalCords;
};
| 341
|
C++
|
.h
| 12
| 25.416667
| 55
| 0.778116
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,582
|
GroundStateFindAlternativeSource.h
|
switchboy_IsoRTS/IsoRTS/scr/Actors/GroundStateFindAlternativeSource.h
|
#pragma once
#include "stateBase.h"
class GroundStateFindAlternativeSource : public StateBase {
public:
using StateBase::StateBase;
bool doAction(Actor* actor) override;
};
| 181
|
C++
|
.h
| 7
| 23.714286
| 59
| 0.793103
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,583
|
heirachicalStateMachineState.h
|
switchboy_IsoRTS/IsoRTS/scr/Actors/heirachicalStateMachineState.h
|
#pragma once
#include "StateBase.h"
class <ClassName> : public StateBase {
public:
bool doAction(Actor* actor) override;
};
| 128
|
C++
|
.h
| 6
| 19.666667
| 41
| 0.754098
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,584
|
SubStateSearchingAlternativeBuildingSpot.h
|
switchboy_IsoRTS/IsoRTS/scr/Actors/SubStateSearchingAlternativeBuildingSpot.h
|
#pragma once
#include "stateBase.h"
class SubStateSearchingAlternativeBuildingSpot : public StateBase {
public:
using StateBase::StateBase;
bool doAction(Actor* actor) override;
};
| 189
|
C++
|
.h
| 7
| 24.857143
| 67
| 0.802198
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,585
|
SubStateSearchNextTarget.h
|
switchboy_IsoRTS/IsoRTS/scr/Actors/SubStateSearchNextTarget.h
|
#pragma once
#include "stateBase.h"
class SubStateSearchNextTarget : public StateBase {
public:
using StateBase::StateBase;
bool doAction(Actor* actor) override;
};
| 173
|
C++
|
.h
| 7
| 22.571429
| 51
| 0.783133
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,586
|
SubStateBuildingTheBuilding.h
|
switchboy_IsoRTS/IsoRTS/scr/Actors/SubStateBuildingTheBuilding.h
|
#pragma once
#include "stateBase.h"
class SubStateBuildingTheBuilding : public StateBase {
public:
using StateBase::StateBase;
bool doAction(Actor* actor) override;
private:
};
| 190
|
C++
|
.h
| 8
| 21.125
| 54
| 0.79096
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,587
|
SubStateWalkingBackFromAction.h
|
switchboy_IsoRTS/IsoRTS/scr/Actors/SubStateWalkingBackFromAction.h
|
#pragma once
#include "stateBase.h"
class SubStateWalkingBackFromAction : public StateBase {
public:
using StateBase::StateBase;
bool doAction(Actor* actor) override;
};
| 178
|
C++
|
.h
| 7
| 23.285714
| 56
| 0.789474
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,588
|
SubStateRangedAttacking.h
|
switchboy_IsoRTS/IsoRTS/scr/Actors/SubStateRangedAttacking.h
|
#pragma once
#include "stateBase.h"
class SubStateRangedAttacking : public StateBase {
public:
using StateBase::StateBase;
bool doAction(Actor* actor) override;
private:
bool checkAndMoveActorToRightOrientation(Actor* actor, cords const targetCords);
void fireProjectile(Actor* actor, cords const targetCords);
};
| 330
|
C++
|
.h
| 10
| 30.4
| 84
| 0.796875
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,589
|
actorStructs.h
|
switchboy_IsoRTS/IsoRTS/scr/Actors/actorStructs.h
|
#pragma once
#include "../globalfunctions.h"
#include "StateNames.h"
enum class FightOrFlight {
fight,
flight
};
enum class targetTypes{
actor,
building,
object,
groundTile,
};
struct stateBackup {
cords _actrorGoal, _actorRealGoal;
BaseStateNames _stateName;
};
struct nearestBuildingTile
{
float deltaDistance;
cords location;
cords actionLocation;
int buildingId;
bool isSet;
int tileId;
};
struct islandCell
{
cords position;
int cellId;
int cellScore;
int parentId;
};
struct routeCell
{
cords position;
bool visited;
int parentCellId;
int backParent;
};
struct orderStack
{
cords goal;
stackOrderTypes orderType;
};
struct unfinischedWalking {
int timePassedSinceChangingOffset;
int timeWalkingBackStarted;
cords position;
cords nPosition;
int speedMultiplier;
//calculations
int startDeltaX = position.x - nPosition.x;
int startDeltaY = position.y - nPosition.y;
float deltaXCompleted = static_cast<float>(startDeltaX) * ((static_cast<float>(this->timePassedSinceChangingOffset) / 1000.f) * (static_cast<float>(this->speedMultiplier) / 1000.f));
float deltaYCompleted = static_cast<float>(startDeltaY) * ((static_cast<float>(this->timePassedSinceChangingOffset) / 1000.f) * (static_cast<float>(this->speedMultiplier) / 1000.f));
};
struct drawXYOverride {
bool isActive;
cords newXY;
};
struct pathedRoute {
std::vector<routeCell> route;
bool pathFound = false;
bool realPath = false;
int timeLastPathTry = 0;
};
| 1,592
|
C++
|
.h
| 67
| 20.19403
| 186
| 0.727032
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,590
|
SubStateSearchingNextSimilairResource.h
|
switchboy_IsoRTS/IsoRTS/scr/Actors/SubStateSearchingNextSimilairResource.h
|
#pragma once
#include "stateBase.h"
class SubStateSearchingNextSimilairResource : public StateBase {
public:
using StateBase::StateBase;
bool doAction(Actor* actor) override;
private:
int _tries = 0;
};
| 217
|
C++
|
.h
| 9
| 21.555556
| 64
| 0.768116
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,591
|
SubStateSearchingAPath.h
|
switchboy_IsoRTS/IsoRTS/scr/Actors/SubStateSearchingAPath.h
|
#pragma once
#include "stateBase.h"
class SubStateSearchingAPath : public StateBase {
public:
using StateBase::StateBase;
bool doAction(Actor* actor) override;
private:
int _tries = 0;
};
| 201
|
C++
|
.h
| 9
| 19.888889
| 49
| 0.753927
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,592
|
GroundStateReturningTheResource.h
|
switchboy_IsoRTS/IsoRTS/scr/Actors/GroundStateReturningTheResource.h
|
#pragma once
#include "stateBase.h"
class GroundStateReturningTheResource : public StateBase {
public:
using StateBase::StateBase;
bool doAction(Actor* actor) override;
};
| 180
|
C++
|
.h
| 7
| 23.571429
| 58
| 0.791908
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,593
|
SubStateDroppingOffResource.h
|
switchboy_IsoRTS/IsoRTS/scr/Actors/SubStateDroppingOffResource.h
|
#pragma once
#include "stateBase.h"
class SubStateDroppingOffResource : public StateBase {
public:
using StateBase::StateBase;
bool doAction(Actor* actor) override;
};
| 176
|
C++
|
.h
| 7
| 23
| 54
| 0.786982
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,594
|
ActorHelper.h
|
switchboy_IsoRTS/IsoRTS/scr/Actors/ActorHelper.h
|
#pragma once
#include "../buildings.h"
namespace actorHelper
{
int actorOrientation(int Xc, int Yc, int Xn, int Yn);
int newOrientation(int oldOrientation, int desiredOrientation);
int adjacentTileIsCorrectDropOffPoint(cords start, resourceTypes resourceGatherd, int team);
bool isReallyNextToResource(int unitX, int unitY, int resourceX, int resourceY);
bool checkIfBuildingIsThereAndIncomplete(const cords& buildinCords, const int& buildingId, const int& actorTeam);
bool isNextToTarget(const cords& a, const cords& b, const int range);
}
| 567
|
C++
|
.h
| 11
| 48.272727
| 117
| 0.787387
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,595
|
BaseStateGathering.h
|
switchboy_IsoRTS/IsoRTS/scr/Actors/BaseStateGathering.h
|
#pragma once
#include "stateBase.h"
#include "../globalfunctions.h"
class BaseStateGathering : public StateBase {
public:
using StateBase::StateBase;
bool doAction(Actor* actor) override;
cords getActionPreformedOn() override;
void setActionPreformedOn(cords location) override;
private:
cords _actionPreformedOn;
};
| 338
|
C++
|
.h
| 12
| 25.416667
| 55
| 0.781538
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,596
|
SubStateSettingMyDecompositionState.h
|
switchboy_IsoRTS/IsoRTS/scr/Actors/SubStateSettingMyDecompositionState.h
|
#pragma once
#include "stateBase.h"
class SubStateSettingMyDecompositionState : public StateBase {
public:
using StateBase::StateBase;
bool doAction(Actor* actor) override;
};
| 184
|
C++
|
.h
| 7
| 24.142857
| 62
| 0.79661
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,597
|
BaseStateDead.h
|
switchboy_IsoRTS/IsoRTS/scr/Actors/BaseStateDead.h
|
#pragma once
#include "stateBase.h"
class BaseStateDead : public StateBase {
public:
using StateBase::StateBase;
bool doAction(Actor* actor) override;
};
| 162
|
C++
|
.h
| 7
| 21
| 41
| 0.767742
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,598
|
SubStateGatheringTheResource.h
|
switchboy_IsoRTS/IsoRTS/scr/Actors/SubStateGatheringTheResource.h
|
#pragma once
#include "stateBase.h"
class SubStateGatheringTheResource : public StateBase {
public:
using StateBase::StateBase;
bool doAction(Actor* actor) override;
};
| 177
|
C++
|
.h
| 7
| 23.142857
| 55
| 0.788235
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,599
|
SubStateSearchingDropOffPoint.h
|
switchboy_IsoRTS/IsoRTS/scr/Actors/SubStateSearchingDropOffPoint.h
|
#pragma once
#include "stateBase.h"
class SubStateSearchingDropOffPoint : public StateBase {
public:
using StateBase::StateBase;
bool doAction(Actor* actor) override;
private:
int _tries = 0;
};
| 208
|
C++
|
.h
| 9
| 20.666667
| 56
| 0.762626
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,600
|
SubStateCountingDownToDestroySelf.h
|
switchboy_IsoRTS/IsoRTS/scr/Actors/SubStateCountingDownToDestroySelf.h
|
#pragma once
#include "stateBase.h"
class SubStateCountingDownToDestroySelf : public StateBase {
public:
using StateBase::StateBase;
bool doAction(Actor* actor) override;
};
| 182
|
C++
|
.h
| 7
| 23.857143
| 60
| 0.794286
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,601
|
SubStateSearchingAlternativeBuildingToBuilt.h
|
switchboy_IsoRTS/IsoRTS/scr/Actors/SubStateSearchingAlternativeBuildingToBuilt.h
|
#pragma once
#include "stateBase.h"
class SubStateSearchingAlternativeBuildingToBuilt : public StateBase {
public:
using StateBase::StateBase;
bool doAction(Actor* actor) override;
};
| 192
|
C++
|
.h
| 7
| 25.285714
| 70
| 0.805405
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,602
|
StateBase.h
|
switchboy_IsoRTS/IsoRTS/scr/Actors/StateBase.h
|
#pragma once
#include "StateNames.h"
#include "../globalfunctions.h"
class Actor; // Forward declaration
class StateBase {
public:
StateBase(BaseStateNames base, GroundStateNames ground, SubStateNames sub) {
_base = base;
_ground = ground;
_sub = sub;
}
virtual bool doAction(Actor* actor);
virtual ModesOfAttack getModeOfAttack();
virtual bool getMoved();
virtual cords getActionPreformedOn();
virtual void setActionPreformedOn(cords location);
BaseStateNames _base;
GroundStateNames _ground;
SubStateNames _sub;
};
| 584
|
C++
|
.h
| 20
| 24.9
| 80
| 0.720641
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,603
|
GroundStateGatheringTheResource.h
|
switchboy_IsoRTS/IsoRTS/scr/Actors/GroundStateGatheringTheResource.h
|
#pragma once
#include "stateBase.h"
class GroundStateGatheringTheResource : public StateBase {
public:
using StateBase::StateBase;
bool doAction(Actor* actor) override;
};
| 180
|
C++
|
.h
| 7
| 23.571429
| 58
| 0.791908
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,604
|
Actor.h
|
switchboy_IsoRTS/IsoRTS/scr/Actors/Actor.h
|
#pragma once
#include <SFML/System.hpp>
#include "actorStructs.h"
#include "../globalfunctions.h"
#include "../actorTemplates.h"
class StateBase;
enum class BaseStateNames;
enum class GroundStateNames;
enum class SubStateNames;
class Actor {
public:
Actor(int type, cords location, int actorTeam, int actorId);
~Actor();
// Copy constructor
Actor(const Actor& other);
// Copy assignment operator
Actor& operator=(const Actor& other);
//State machine
void switchBaseState(BaseStateNames desiredState);
void switchGroundState(GroundStateNames desiredState);
void switchSubState(SubStateNames desiredState);
//Interact
void takeDamage(int amountOfDamage, int idOfAttacker, targetTypes typeOfAttacker);
void stackOrder(cords Goal, stackOrderTypes orderType);
void clearCommandStack();
//Updateing
void update();
void calculateRoute(); //marked for deletion
//Drawing & animation
void drawActor();
void renderPath();
void printActorDebugText();
void animateWalkingToAndFromAction(bool from);
void animateWalkingToAction();
void animatWalkingBackFromAction();
//Getters
int getActorId() const;
bool getIsAlive() const;
bool getIsGathering() const;
bool getIsIdle() const;
bool getIsBuilding() const;
resourceTypes getResourceGathered() const;
std::pair<int, int> getHealth() const;
bool getHasRoute();
cords getGoal() const;
cords getRealGoal() const;
cords getActorCords() const;
int getTeam() const;
int getMeleeDMG() const;
int getRangedDMG() const;
sf::IntRect getLastIntRect() const;
const std::list<cords>& getRejectedTargetsList() const;
std::string getNameOfActor() const;
int getType() const;
std::string getResources() const;
int getBuildingId() const;
//pathfinding
void pathAStar();
private:
bool doNextStackedCommand();
void makeSureActorIsOnTheMap();
StateBase* _baseState;
StateBase* _groundState;
StateBase* _subState;
int _actorType, _actorHealth, _hitPoints, _actorId, _actorTeam, _meleeDamage, _rangedDamage, _amountOfWood, _amountOfFood, _amountOfStone,
_amountOfGold, _buildingId, _range, _timeBetweenShots, _splashDamage, _projectileType, _doesRangedDamage, _rateOfFire, _timeToCrossOneTile,
_spriteYOffset, _timeLastOffsetChange, _orientation, _offSetX, _offSetY, _timeLastUpdate;
bool _cantPassActors;
cords _actorGoal, _actorCords, _actorRealGoal;
sf::IntRect _lastIntRect;
std::list<cords> _listOfTargetsToRejectUntilSuccesfullMovement;
pathedRoute _route;
std::list<orderStack> _listOfOrders;
resourceTypes _resourceBeingGatherd;
stateBackup _previousState;
//temp
std::vector<sf::String> _actorDeclaringString;
//Actor modifiers
void updateGoal(cords goal, int waitTime);
friend class StateBase;
friend class StateCanceledWhileWalking;
//Base states
friend class BaseStateIdle;
friend class BaseStateWalkingAToB;
friend class BaseStateBuilding;
friend class BaseStateGathering;
friend class BaseStateFighting;
friend class BaseStateDead;
//Ground states
friend class GroundStateWalking;
friend class GroundStateGatheringTheResource;
friend class GroundStateReturningTheResource;
friend class GroundStateBuildingTheBuilding;
friend class GroundStateAttacking;
friend class GroundStateFleeing;
friend class GroundStateDecomposing;
friend class GroundStateFindAlternativeSource;
friend class GroundStateSearchAlternativeBuildingSpot;
//Sub states
friend class SubStateWalkingToNextSquare;
friend class SubStateSearchingAPath;
friend class SubStateSearchingNextSimilairResource;
friend class SubStateSearchingDropOffPoint;
friend class SubStateSearchingAlternativeBuildingSpot;
friend class SubStateSearchingAlternativeBuildingToBuilt;
friend class SubStateMeleeAttacking;
friend class SubStateRangedAttacking;
friend class SubStateSearchNextTarget;
friend class SubStateSettingGoalToFleeTo;
friend class SubStateSettingMyDecompositionState;
friend class SubStateCountingDownToDestroySelf;
friend class SubStateWalkingToAction;
friend class SubStateWalkingBackFromAction;
friend class SubStateBuildingTheBuilding;
friend class SubStateGatheringTheResource;
friend class SubStateDroppingOffResource;
friend class SubStateFindingNewTarget;
};
extern std::vector <Actor> listOfActors;
extern std::vector<int> listOfActorsWhoNeedAPath;
extern nearestBuildingTile findNearestBuildingTile(int buildingId, int actorId);
| 4,683
|
C++
|
.h
| 121
| 33.991736
| 147
| 0.774279
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,605
|
GroundStateWalking.h
|
switchboy_IsoRTS/IsoRTS/scr/Actors/GroundStateWalking.h
|
#pragma once
#include "stateBase.h"
class GroundStateWalking : public StateBase {
public:
using StateBase::StateBase;
bool doAction(Actor* actor) override;
};
| 167
|
C++
|
.h
| 7
| 21.714286
| 45
| 0.775
|
switchboy/IsoRTS
| 33
| 10
| 0
|
GPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,606
|
Controller.cpp
|
qutescoop_qutescoop/src/Controller.cpp
|
#include "Controller.h"
#include "Airport.h"
#include "Client.h"
#include "NavData.h"
#include "Settings.h"
#include "Whazzup.h"
#include "dialogs/ControllerDetails.h"
#include "helpers.h"
#include "src/mustache/Renderer.h"
#include <QJsonObject>
const QRegularExpression Controller::cpdlcRegExp = QRegularExpression(
"\\b([A-Z]{3}[A-Z0-9])\\b.{0,5}CPDLC|CPDLC.{0,25}\\b([A-Z]{3}[A-Z0-9])\\b",
QRegularExpression::MultilineOption | QRegularExpression::InvertedGreedinessOption
);
Controller::Controller(const QJsonObject& json, const WhazzupData* whazzup)
: MapObject(), Client(json, whazzup),
frequency(""),
atisMessage(""), atisCode(""), facilityType(0),
visualRange(0), sector(0) {
frequency = json["frequency"].toString();
Q_ASSERT(!frequency.isNull());
facilityType = json["facility"].toInt();
if (callsign.right(4) == "_FSS") {
facilityType = 7; // workaround as VATSIM reports 1 for _FSS
}
visualRange = json["visual_range"].toInt();
atisMessage = "";
if (json.contains("text_atis") && json["text_atis"].isArray()) {
QJsonArray atis = json["text_atis"].toArray();
for (int i = 0; i < atis.size(); ++i) {
atisMessage += atis[i].toString() + "\n";
}
}
atisCode = "";
if (json.contains("atis_code")) {
atisCode = json["atis_code"].isNull()? "": json["atis_code"].toString();
}
// do some magic for Controller Info like "online until"...
QRegExp rxOnlineUntil = QRegExp(
"(open|close|online|offline|till|until)(\\W*\\w*\\W*){0,4}\\b(\\d{1,2}):?(\\d{2})\\W?(z|utc)?",
Qt::CaseInsensitive
);
if (rxOnlineUntil.indexIn(atisMessage) > 0) {
QTime found = QTime::fromString(rxOnlineUntil.cap(3) + rxOnlineUntil.cap(4), "HHmm");
if (found.isValid()) {
if (qAbs(found.secsTo(whazzup->whazzupTime.time())) > 60 * 60 * 12) {
// e.g. now its 2200z, and he says "online until 0030z", allow for up to 12 hours
assumeOnlineUntil = QDateTime(whazzup->whazzupTime.date().addDays(1), found, Qt::UTC);
} else {
assumeOnlineUntil = QDateTime(whazzup->whazzupTime.date(), found, Qt::UTC);
}
}
}
QString icao = controllerSectorName();
// Look for a sector name prefix matching the login
if (!icao.isEmpty()) {
do {
foreach (const auto _sector, NavData::instance()->sectors.values(icao)) {
if (_sector->controllerSuffixes().isEmpty()) {
sector = _sector;
break;
}
foreach (const auto suffix, _sector->controllerSuffixes()) {
if (callsign.endsWith(suffix)) {
sector = _sector;
break;
}
}
}
if (sector != 0) {
// We determine lat/lon from the sector
QPair<double, double> center = this->sector->getCenter();
if (center.first > -180.) {
lat = center.first;
lon = center.second;
}
break;
}
icao.chop(1);
} while (icao.length() >= 2);
if (sector == 0) {
QString msg("Unknown sector/FIR " + controllerSectorName() + " - Please provide sector information if you can.");
qInfo() << msg;
QTextStream(stdout) << "INFO: " << msg << Qt::endl;
}
} else {
// We try to get lat/lng from covered airports
auto _airports = airports();
if (_airports.size() > 0) {
auto _a = *_airports.constBegin();
lat = _a->lat;
lon = _a->lon;
}
}
}
Controller::~Controller() {
MustacheQs::Renderer::teardownContext(this);
}
QString Controller::facilityString() const {
switch (facilityType) {
case 0: return "OBS";
case 1: return "Staff";
case 2: return "DEL";
case 3: return "GND";
case 4: return "TWR";
case 5: return "APP";
case 6: return "CTR";
case 7: return "FSS";
}
return QString();
}
QString Controller::typeString() const {
const auto labelTokens = atcLabelTokens();
if (labelTokens.isEmpty()) {
return "";
}
return labelTokens.constLast();
}
QStringList Controller::atcLabelTokens() const {
if (!isATC()) {
return QStringList();
}
return callsign.split('_', Qt::SkipEmptyParts);
}
QString Controller::controllerSectorName() const {
auto _atcLabelTokens = atcLabelTokens();
if (
!_atcLabelTokens.empty()
&& (_atcLabelTokens.last().startsWith("CTR") || _atcLabelTokens.last().startsWith("FSS"))
) {
_atcLabelTokens.removeLast();
return _atcLabelTokens.join("_");
}
return QString();
}
QString Controller::livestreamString() const {
return Client::livestreamString(atisMessage);
}
bool Controller::isCtrFss() const {
// https://vatsim.net/docs/policy/global-controller-administration-policy
// we are ignoring these:
// _TMU, _FMP: ยง 4.5(l) Traffic Flow Position
// A traffic flow position does not provide any control instructions for pilots.
// _RDO: ยง 6.6 Radio Operator positions must be [..] online with an associated controller.
return callsign.endsWith("_CTR") || callsign.endsWith("_FSS");
}
bool Controller::isAppDep() const {
return callsign.endsWith("_APP") || callsign.endsWith("_DEP");
}
bool Controller::isTwr() const {
return callsign.endsWith("_TWR");
}
bool Controller::isGnd() const {
return callsign.endsWith("_GND") || callsign.endsWith("_RMP");
}
bool Controller::isDel() const {
return callsign.endsWith("_DEL");
}
bool Controller::isAtis() const {
return callsign.endsWith("_ATIS");
}
QSet <Airport*> Controller::airports(bool withAdditionalMatches) const {
auto airports = QSet<Airport*>();
auto _atcLabelTokens = atcLabelTokens();
if (_atcLabelTokens.empty()) {
return airports;
}
auto prefix = _atcLabelTokens.constFirst();
// ordinary / normal match EDDS_STG_APP -> EDDS
auto a = NavData::instance()->airports.value(prefix, 0);
if (a != 0) {
airports.insert(a);
}
if (withAdditionalMatches) {
auto suffix = _atcLabelTokens.constLast();
// use matches from controllerAirportsMapping.dat
auto _airports = NavData::instance()->additionalMatchedAirportsForController(prefix, suffix);
foreach (const auto& _a, _airports) {
airports.insert(_a);
}
}
// if(sector != 0) {
// foreach(auto* a, NavData::instance()->airports) {
// if(sector->containsPoint(QPointF(a->lat, a->lon))) {
// airports.insert(a);
// }
// }
// }
// if we have not had any match yet and since some
// VATSIMmers still don't think ICAO codes are cool
// IAH_TWR -> IAH
if (airports.isEmpty() && prefix.length() == 3) {
auto a = NavData::instance()->airports.value("K" + prefix, 0);
if (a != 0) {
airports.insert(a);
}
}
return airports;
}
QList <Airport*> Controller::airportsSorted() const {
auto _airports = airports().values();
// sort by congestion
std::sort(
_airports.begin(),
_airports.end(),
[](const Airport* a, const Airport* b)->bool {
return a->congestion() > b->congestion();
}
);
return _airports;
}
const QString Controller::cpdlcString(const QString& prepend, bool alwaysWithIdentifier) const {
if (atisMessage.isEmpty()) {
return "";
}
auto match = Controller::cpdlcRegExp.match(atisMessage);
if (match.hasMatch()) {
auto logon = match.capturedRef(match.lastCapturedIndex());
if (!alwaysWithIdentifier && callsign.startsWith(logon)) {
// found perfect match
return prepend;
}
return prepend + logon;
}
return "";
}
void Controller::showDetailsDialog() {
ControllerDetails* infoDialog = ControllerDetails::instance();
infoDialog->refresh(this);
infoDialog->show();
infoDialog->raise();
infoDialog->activateWindow();
infoDialog->setFocus();
}
QString Controller::rank() const {
return Whazzup::instance()->realWhazzupData().ratings.value(rating, QString());
}
bool Controller::isFriend() const {
if (isAtis()) {
return false;
}
return Client::isFriend();
}
QString Controller::toolTip() const { // LOVV_CTR [Vienna] (134.350, Alias | Name, C1)
QString result = callsign;
if (sector != 0) {
result += " [" + sector->name + "]";
}
result += " (";
if (!isObserver() && !frequency.isEmpty()) {
result += frequency + ", ";
}
result += realName();
if (!rank().isEmpty()) {
result += ", " + rank();
}
result += ")";
return result;
}
QString Controller::toolTipShort() const // LOVV_CTR [Vienna]
{
QString result = callsign;
if (sector != 0) {
result += " [" + sector->name + "]";
}
return result;
}
QString Controller::mapLabel() const {
auto tmpl = Settings::firPrimaryContent();
return MustacheQs::Renderer::render(tmpl, (QObject*) this);
}
QString Controller::mapLabelHovered() const {
auto tmpl = Settings::firPrimaryContentHovered();
return MustacheQs::Renderer::render(tmpl, (QObject*) this);
}
QStringList Controller::mapLabelSecondaryLines() const {
auto tmpl = Settings::firSecondaryContent();
return Helpers::linesFilteredTrimmed(
MustacheQs::Renderer::render(tmpl, (QObject*) this)
);
}
QStringList Controller::mapLabelSecondaryLinesHovered() const {
auto tmpl = Settings::firSecondaryContentHovered();
return Helpers::linesFilteredTrimmed(
MustacheQs::Renderer::render(tmpl, (QObject*) this)
);
}
bool Controller::matches(const QRegExp& regex) const {
return frequency.contains(regex)
|| atisMessage.contains(regex)
|| realName().contains(regex)
|| (sector != 0 && sector->name.contains(regex))
|| MapObject::matches(regex);
}
bool Controller::hasPrimaryAction() const {
return true;
}
void Controller::primaryAction() {
showDetailsDialog();
}
bool Controller::isObserver() const {
return facilityType == 0;
}
bool Controller::isATC() const {
// 199.998 gets transmitted on VATSIM for a controller without prim freq
Q_ASSERT(!frequency.isNull());
return facilityType > 0 && !frequency.isEmpty() && frequency != "199.998";
}
| 10,712
|
C++
|
.cpp
| 308
| 28.396104
| 125
| 0.609737
|
qutescoop/qutescoop
| 33
| 15
| 21
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,607
|
FileReader.cpp
|
qutescoop_qutescoop/src/FileReader.cpp
|
#include "FileReader.h"
FileReader::FileReader(const QString& filename) {
_stream = 0;
_file = new QFile(filename);
if (!_file->open(QIODevice::ReadOnly | QIODevice::Text)) {
delete _file;
_file = 0;
return;
}
_stream = new QTextStream(_file);
}
FileReader::~FileReader() {
if (_file != 0) {
delete _file;
}
if (_stream != 0) {
delete _stream;
}
}
QString FileReader::nextLine() const {
if (_stream == 0 || _stream->atEnd()) {
return QString();
}
return _stream->readLine();
}
bool FileReader::atEnd() const {
if (_stream == 0) {
return true;
}
return _stream->atEnd();
}
| 693
|
C++
|
.cpp
| 31
| 17.451613
| 62
| 0.564688
|
qutescoop/qutescoop
| 33
| 15
| 21
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,608
|
Tessellator.cpp
|
qutescoop_qutescoop/src/Tessellator.cpp
|
#include "Tessellator.h"
#include "helpers.h"
GLdouble vertices[64][6]; // newly created vertices (x,y,z,r,g,b) by combine callback
int vertexIndex; // array index for above array incremented inside combine callback
Tessellator::Tessellator() {
_tess = gluNewTess();
gluTessCallback(_tess, GLU_TESS_BEGIN, CALLBACK_CAST tessBeginCB);
gluTessCallback(_tess, GLU_TESS_END, CALLBACK_CAST tessEndCB);
gluTessCallback(_tess, GLU_TESS_ERROR, CALLBACK_CAST tessErrorCB);
gluTessCallback(_tess, GLU_TESS_VERTEX, CALLBACK_CAST tessVertexCB);
gluTessCallback(_tess, GLU_TESS_COMBINE, CALLBACK_CAST tessCombineCB);
}
Tessellator::~Tessellator() {
gluDeleteTess(_tess);
}
void Tessellator::tessellate(const QList<QPair<double, double> >& points) {
// tessellate and compile polygon into display list
// gluTessVertex() takes 3 params: tess object, pointer to vertex coords,
// and pointer to vertex data to be passed to vertex callback.
// The second param is used only to perform tessellation, and the third
// param is the actual vertex data to draw. It is usually same as the second
// param, but It can be more than vertex coord, for example, color, normal
// and UV coords which are needed for actual drawing.
// Here, we are looking at only vertex coods, so the 2nd and 3rd params are
// pointing to the same address.
_pointList.clear();
vertexIndex = 0;
gluTessBeginPolygon(_tess, 0);
gluTessBeginContour(_tess);
for (int i = 0; i < points.size(); i++) {
GLdouble* p = new GLdouble[3];
_pointList.append(p);
p[0] = SXhigh(points[i].first, points[i].second);
p[1] = SYhigh(points[i].first, points[i].second);
p[2] = SZhigh(points[i].first, points[i].second);
gluTessVertex(_tess, p, p);
}
gluTessEndContour(_tess);
gluTessEndPolygon(_tess);
for (int i = 0; i < _pointList.size(); i++) {
delete _pointList[i];
}
_pointList.clear();
}
CALLBACK_DECL Tessellator::tessErrorCB(GLenum errorCode) {
qCritical() << (char*) gluErrorString(errorCode);
}
CALLBACK_DECL Tessellator::tessBeginCB(GLenum which) {
glBegin(which);
}
CALLBACK_DECL Tessellator::tessEndCB() {
glEnd();
}
CALLBACK_DECL Tessellator::tessVertexCB(const GLvoid* data) {
const GLdouble* ptr = (const GLdouble*) data;
glVertex3dv(ptr);
}
///////////////////////////////////////////////////////////////////////////////
// Combine callback is used to create a new vertex where edges intersect.
// In this function, copy the vertex data into local array and compute the
// color of the vertex. And send it back to tessellator, so tessellator pass it
// to vertex callback function.
//
// newVertex: the intersect point which tessellator creates for us
// neighborVertex[4]: 4 neighbor vertices to cause intersection (given from 3rd param of gluTessVertex()
// neighborWeight[4]: 4 interpolation weights of 4 neighbor vertices
// outData: the vertex data to return to tessellator
///////////////////////////////////////////////////////////////////////////////
CALLBACK_DECL Tessellator::tessCombineCB(
const GLdouble newVertex[3],
const GLdouble*[4],
const GLfloat [4],
GLdouble** outData
) {
// copy new intersect vertex to local array
// Because newVertex is temporal and cannot be hold by tessellator until next
// vertex callback called, it must be copied to the safe place in the app.
// Once gluTessEndPolygon() called, then you can safly deallocate the array.
vertices[vertexIndex][0] = newVertex[0];
vertices[vertexIndex][1] = newVertex[1];
vertices[vertexIndex][2] = newVertex[2];
// return output data (vertex coords and others)
*outData = vertices[vertexIndex]; // assign the address of new intersect vertex
++vertexIndex; // increase index for next vertex
}
| 3,874
|
C++
|
.cpp
| 85
| 41.576471
| 104
| 0.688659
|
qutescoop/qutescoop
| 33
| 15
| 21
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,609
|
FriendsVisitor.cpp
|
qutescoop_qutescoop/src/FriendsVisitor.cpp
|
#include "Client.h"
#include "FriendsVisitor.h"
FriendsVisitor::FriendsVisitor() {}
void FriendsVisitor::visit(MapObject* object) {
Client* c = dynamic_cast<Client*>(object);
if (c == 0) {
return;
}
if (!c->isFriend()) {
return;
}
MapObject* m = dynamic_cast<MapObject*>(object);
if (m != 0) {
m_friends.append(m);
}
}
QList<MapObject*> FriendsVisitor::result() const {
return m_friends;
}
| 454
|
C++
|
.cpp
| 19
| 19.526316
| 52
| 0.61949
|
qutescoop/qutescoop
| 33
| 15
| 21
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,610
|
MetarDelegate.cpp
|
qutescoop_qutescoop/src/MetarDelegate.cpp
|
#include "MetarDelegate.h"
#include <QApplication>
void MetarDelegate::paint(QPainter* painter, const QStyleOptionViewItem &option, const QModelIndex &index) const {
if (!index.data().isValid()) {
return;
}
QStyleOptionViewItem opt = option;
initStyleOption(&opt, index);
Q_ASSERT(opt.widget);
const QStyle* style = opt.widget->style();
style->drawPrimitive(QStyle::PE_PanelItemViewItem, &opt, painter, opt.widget);
const int hMargin = style->pixelMetric(QStyle::PM_FocusFrameHMargin) + 2;
const int vMargin = style->pixelMetric(QStyle::PM_FocusFrameVMargin) + 2;
const QRect contentRect = QRect(
opt.rect.x() + hMargin,
opt.rect.y() + vMargin,
opt.rect.width() - 2 * hMargin,
opt.rect.height() - 2 * vMargin
);
painter->save();
const QRect alignedRect = style->alignedRect(
opt.direction,
Qt::AlignTop,
contentRect.size(),
contentRect
);
painter->setFont(opt.font);
style->drawItemText(
painter,
alignedRect,
Qt::TextWordWrap,
QApplication::palette(),
opt.state & QStyle::State_Enabled,
index.data().toString()
);
painter->restore();
}
QSize MetarDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const {
if (!index.data().isValid()) {
return QSize(0, 0);
}
QStyleOptionViewItem opt = option;
initStyleOption(&opt, index);
Q_ASSERT(opt.widget);
const QStyle* style = opt.widget->style();
const int hMargin = style->pixelMetric(QStyle::PM_FocusFrameHMargin) + 2;
const int vMargin = style->pixelMetric(QStyle::PM_FocusFrameVMargin) + 2;
const int scrollBarWidth = style->pixelMetric(QStyle::PM_ScrollBarExtent);
const int width = opt.widget->width() - 2 * hMargin - scrollBarWidth;
const QRect textArea = QRect(
hMargin,
vMargin,
width,
1000
);
const QRect textRect = style->itemTextRect(
opt.fontMetrics,
textArea,
Qt::TextWordWrap,
opt.state & QStyle::State_Enabled,
index.data().toString()
);
return QSize(0, textRect.height() + 2 * vMargin);
}
| 2,224
|
C++
|
.cpp
| 64
| 28.359375
| 114
| 0.652538
|
qutescoop/qutescoop
| 33
| 15
| 21
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,611
|
MapScreen.cpp
|
qutescoop_qutescoop/src/MapScreen.cpp
|
#include "MapScreen.h"
static MapScreen* mapScreenInstance = 0;
MapScreen* MapScreen::instance(bool createIfNoInstance) {
if (mapScreenInstance == 0 && createIfNoInstance) {
mapScreenInstance = new MapScreen;
}
return mapScreenInstance;
}
MapScreen::MapScreen(QWidget* parent)
: QWidget(parent) {
//OpenGL config
QSettings* settings = new QSettings();
QGLFormat fmt;
fmt.setDirectRendering(settings->value("gl/directrendering", fmt.defaultFormat().directRendering()).toBool());
fmt.setDoubleBuffer(settings->value("gl/doublebuffer", fmt.defaultFormat().doubleBuffer()).toBool());
fmt.setStencil(settings->value("gl/stencilbuffer", fmt.defaultFormat().stencil()).toBool());
if (fmt.defaultFormat().stencilBufferSize() > 0) {
fmt.setStencilBufferSize(settings->value("gl/stencilsize", fmt.defaultFormat().stencilBufferSize()).toInt());
}
fmt.setDepth(settings->value("gl/depthbuffer", fmt.defaultFormat().depth()).toBool());
if (fmt.defaultFormat().depthBufferSize() > 0) {
fmt.setDepthBufferSize(settings->value("gl/depthsize", fmt.defaultFormat().depthBufferSize()).toInt());
}
fmt.setAlpha(settings->value("gl/alphabuffer", fmt.defaultFormat().alpha()).toBool());
if (fmt.defaultFormat().alphaBufferSize() > 0) {
fmt.setAlphaBufferSize(settings->value("gl/alphasize", fmt.defaultFormat().alphaBufferSize()).toInt());
}
fmt.setAccum(settings->value("gl/accumbuffer", fmt.defaultFormat().accum()).toBool());
if (fmt.defaultFormat().accumBufferSize() > 0) {
fmt.setAccumBufferSize(settings->value("gl/accumsize", fmt.defaultFormat().accumBufferSize()).toInt());
}
fmt.setRgba(true);
// Anti-aliasing (4xMSAA by default):
const auto sampleBuffers = settings->value("gl/samplebuffers", true).toBool();
if (sampleBuffers) {
const auto nSamples = settings->value("gl/samples", 4).toInt();
fmt.setSamples(nSamples);
qDebug() << "GLFormat: MSAA: Requesting multi-sample anti-aliasing with" << nSamples << "sample buffers";
}
fmt.setSampleBuffers(sampleBuffers);
qDebug() << "creating GLWidget";
glWidget = new GLWidget(fmt, this);
QGridLayout* layout = new QGridLayout;
layout->setContentsMargins(0, 0, 0, 0);
layout->setMargin(0);
layout->addWidget(glWidget);
setLayout(layout);
qDebug() << "creating GLWidget --finished";
}
void MapScreen::resizeEvent(QResizeEvent*) {
glWidget->resize(this->width(), this->height());
}
| 2,540
|
C++
|
.cpp
| 52
| 43.5
| 117
| 0.701215
|
qutescoop/qutescoop
| 33
| 15
| 21
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,612
|
QuteScoop.cpp
|
qutescoop_qutescoop/src/QuteScoop.cpp
|
#include "Airac.h"
#include "Launcher.h"
#include "NavData.h"
#include "Platform.h"
#include "Settings.h"
#include "src/Airport.h"
#include <QApplication>
#include <QMessageBox>
#include <QtCore>
/* logging */
QScopedPointer<QFile> m_logFile;
void messageHandler(QtMsgType type, const QMessageLogContext& a, const QString& msg) {
const QMap<QtMsgType, QString> typeStrings {
{ QtInfoMsg, "INFO" },
{ QtDebugMsg, "DBG" },
{ QtWarningMsg, "WARN" },
{ QtCriticalMsg, "CRIT" },
{ QtFatalMsg, "FATAL" },
};
const QString function(a.function);
const auto line = QString("[%1] %2 +%5 %4 %3").arg(
typeStrings.value(type),
QFileInfo(a.file).fileName(),
msg,
function
).arg(a.line);
QTextStream stdoutStream(stdout);
// useful for ad-hoc stdout debugging with all the nice QDebug type conversions, too
if (type == QtCriticalMsg || type == QtFatalMsg) {
stdoutStream << line << Qt::endl;
}
QTextStream out(m_logFile.data());
out << QDateTime::currentDateTimeUtc().toString("HH:mm:ss.zzz[Z]") << " " << line << Qt::endl;
out.flush();
}
/* main */
int main(int argc, char* argv[]) {
QApplication app(argc, argv); // before QT_REQUIRE_VERSION to prevent creating duplicate..
QT_REQUIRE_VERSION(argc, argv, "5.15.0"); // ..application objects
// some app init
app.setOrganizationName("QuteScoop");
app.setOrganizationDomain("qutescoop.github.io");
app.setApplicationName("QuteScoop");
app.setApplicationVersion(Platform::version());
app.setWindowIcon(QIcon(QPixmap(":/icons/qutescoop.png")));
//QLocale::setDefault(QLocale::C); // bullet-proof string->float conversions
// this can be removed in Qt6 https://bugreports.qt.io/browse/QTBUG-70431
QApplication::setAttribute(Qt::AA_DisableWindowContextHelpButton);
// Open log.txt
m_logFile.reset(new QFile(Settings::dataDirectory("log.txt")));
m_logFile.data()->open(QFile::WriteOnly | QFile::Text);
// catch all messages
qInstallMessageHandler(messageHandler);
// stdout
QTextStream(stdout) << "Log output can be found in " << Settings::dataDirectory("log.txt") << Qt::endl;
QTextStream(stdout) << "Using settings from " << Settings::fileName() << Qt::endl;
// some initial debug logging
qDebug().noquote() << "QuteScoop" << Platform::version();
qDebug() << "Using settings from" << Settings::fileName();
qDebug() << "Using application data from" << Settings::dataDirectory();
qDebug().noquote() << QString("Compiled with Qt %1 [%4, mode: %2], running with Qt %3 on %5.").arg(
QT_VERSION_STR, Platform::compileMode(), qVersion(), Platform::compiler(), Platform::platformOS()
);
// image format plugins
app.addLibraryPath(QString("%1/imageformats").arg(app.applicationDirPath()));
qDebug() << "Library paths:" << app.libraryPaths();
qDebug() << "Supported image formats:" << QImageReader::supportedImageFormats();
// command line parameters
QCommandLineParser parser;
parser.addHelpOption();
QCommandLineOption routeOption(
{ "r", "route" },
"resolve route",
"<dep> <route> <dest>"
);
parser.addOptions({ routeOption });
parser.process(app);
if (parser.isSet(routeOption)) { // resolves a route
if (parser.positionalArguments().size() < 1) {
QTextStream(stdout) << "ERROR: need at least 2 arguments" << Qt::endl;
return 1;
}
auto navData = NavData::instance();
navData->load();
auto airac = Airac::instance();
airac->load();
const auto depString = parser.value(routeOption);
QStringList route = parser.positionalArguments();
route.prepend(depString);
QTextStream(stdout) << "" << Qt::endl << "# Flightplan route:" << Qt::endl << route.join(" ") << Qt::endl;
const auto dep = NavData::instance()->airports.value(depString, 0);
if (dep == 0) {
QTextStream(stdout) << "ERROR: departure aerodrome not found in database" << Qt::endl;
return 1;
}
const auto waypoints = Airac::instance()->resolveFlightplan(route, dep->lat, dep->lon, Airac::ifrMaxWaypointInterval);
QTextStream(stdout) << "" << Qt::endl << "# Waypoints:" << Qt::endl;
Waypoint* _prevW = nullptr;
float distAccum = 0;
foreach (const auto &w, waypoints) {
QString _prevDetails;
if (_prevW != nullptr) {
float _dist = NavData::distance(w->lat, w->lon, _prevW->lat, _prevW->lon);
_prevDetails = QString("→ %1°, %2NM")
.arg(NavData::courseTo(w->lat, w->lon, _prevW->lat, _prevW->lon), 5, 'f', 1, '0')
.arg(_dist, 0, 'f', 1)
;
distAccum += _dist;
}
QTextStream(stdout) << _prevDetails
<< Qt::endl
<< w->id
<< Qt::endl
<< QString(" location: %1 (%2)").arg(NavData::toEurocontrol(w->lat, w->lon), QString("%1/%2").arg(w->lat).arg(w->lon))
<< Qt::endl
<< QString(" accum: %1NM").arg(distAccum, 0, 'f', 1)
<< Qt::endl
;
QStringList airways;
foreach (const auto &awyList, airac->airways) {
foreach (const auto &a, awyList) {
if (a->waypoints().contains(w)) {
airways << a->name;
}
}
}
if (!airways.isEmpty()) {
QTextStream(stdout) << "\tairways: " << airways.join(", ") << Qt::endl;
}
_prevW = w;
}
return 0;
}
// show Launcher
Launcher::instance()->fireUp();
// start event loop
return app.exec();
}
| 6,031
|
C++
|
.cpp
| 138
| 34.42029
| 152
| 0.576083
|
qutescoop/qutescoop
| 33
| 15
| 21
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,613
|
Client.cpp
|
qutescoop_qutescoop/src/Client.cpp
|
#include "Client.h"
#include "Settings.h"
#include "Whazzup.h"
#include <QInputDialog>
const QRegularExpression Client::livestreamRegExp = QRegularExpression(
"("
"(twitch)(\\.tv)?"
"|(youtu\\.?be)(\\.com)?"
"|(owncast)(\\.online)?"
")"
"\\W([^ |\\n]+)",
QRegularExpression::MultilineOption | QRegularExpression::CaseInsensitiveOption
);
QString Client::livestreamString(const QString& str) {
auto matchIterator = livestreamRegExp.globalMatch(str);
// take last match. Helps with "live on twitch now: twitch/user"
while (matchIterator.hasNext()) {
auto match = matchIterator.next();
if (!matchIterator.hasNext()) {
QString network(match.captured(2) + match.captured(4) + match.captured(6));
return network.toLower() + "/" + match.capturedRef(8);
}
}
return "";
}
Client::Client(const QJsonObject& json, const WhazzupData*)
: callsign(""), userId(""), homeBase(""), server(""), rating(-99) {
callsign = json["callsign"].toString();
if (callsign.isNull()) {
callsign = "";
}
userId = QString::number(json["cid"].toInt());
server = json["server"].toString();
rating = json["rating"].toInt();
timeConnected = QDateTime::fromString(json["logon_time"].toString(), Qt::ISODate);
m_nameOrCid = json["name"].toString();
if (m_nameOrCid.isNull()) {
m_nameOrCid = "";
}
if (m_nameOrCid.contains(QRegExp("\\b[A-Z]{4}$"))) {
homeBase = m_nameOrCid.right(4);
m_nameOrCid = m_nameOrCid.chopped(4).trimmed();
}
}
QString Client::onlineTime() const {
if (!timeConnected.isValid()) {
return QString("not connected");
}
return QDateTime::fromTime_t(
// this will get wrapped by 24h but that should not be a problem...
Whazzup::instance()->whazzupData().whazzupTime.toTime_t()
- timeConnected.toTime_t()
).toUTC().toString("HH:mm") + " hrs";
}
QString Client::displayName(bool withLink) const {
QString result = realName();
if (!rank().isEmpty()) {
result += " (" + rank() + ")";
}
if (withLink && hasValidID()) {
QString link = Whazzup::instance()->userUrl(userId);
if (link.isEmpty()) {
return result;
}
result = QString("<a href='%1'>%2</a>").arg(link, result.toHtmlEscaped());
}
return result;
}
QString Client::detailInformation() const {
if (!homeBase.isEmpty()) {
return "(" + homeBase + ")";
}
return "";
}
bool Client::showAliasDialog(QWidget* parent) const {
bool ok;
QString alias = QInputDialog::getText(
parent,
QString("Edit alias"),
QString("Set the alias for %1 [empty to unset]:").arg(nameOrCid()),
QLineEdit::Normal,
Settings::clientAlias(userId),
&ok
);
if (ok) {
Settings::setClientAlias(userId, alias);
}
return ok;
}
bool Client::isValidID(const QString id) {
return !id.isEmpty() && id.toInt() >= 800000;
}
bool Client::matches(const QRegExp& regex) const {
return m_nameOrCid.contains(regex)
|| userId.contains(regex);
}
QString Client::rank() const {
return "";
}
QString Client::livestreamString() const {
return "";
}
bool Client::isFriend() const {
return Settings::friends().contains(userId);
}
const QString Client::realName() const {
auto& _alias = Settings::clientAlias(userId);
if (!_alias.isEmpty() && _alias != m_nameOrCid) {
return _alias + " | " + m_nameOrCid;
}
return m_nameOrCid;
}
const QString Client::nameOrCid() const {
return m_nameOrCid;
}
const QString Client::aliasOrName() const {
auto _alisOrNameOrCid = aliasOrNameOrCid();
if (isValidID(_alisOrNameOrCid)) {
return "";
}
return _alisOrNameOrCid;
}
const QString Client::aliasOrNameOrCid() const {
auto& _alias = Settings::clientAlias(userId);
if (!_alias.isEmpty()) {
return _alias;
}
return m_nameOrCid;
}
bool Client::hasValidID() const {
return Client::isValidID(userId);
}
| 4,099
|
C++
|
.cpp
| 132
| 25.954545
| 87
| 0.626714
|
qutescoop/qutescoop
| 33
| 15
| 21
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,614
|
Airac.cpp
|
qutescoop_qutescoop/src/Airac.cpp
|
#include "Airac.h"
#include "Airport.h"
#include "FileReader.h"
#include "GuiMessage.h"
#include "NavData.h"
#include "Settings.h"
#include "Waypoint.h"
Airac* airacInstance = 0;
Airac* Airac::instance(bool createIfNoInstance) {
if (airacInstance == 0) {
if (createIfNoInstance) {
airacInstance = new Airac();
}
}
return airacInstance;
}
QString Airac::effectiveCycle(const QDate &date) {
auto effectiveDate = QDate(2016, 1, 7);
int year = 0, release = 0;
do {
if (effectiveDate.year() != year) {
year = effectiveDate.year();
release = 0;
}
release++;
effectiveDate = effectiveDate.addDays(28);
} while (effectiveDate < date);
return QString::number(year).right(2) + QString::number(release).rightJustified(2, '0');
}
Airac::Airac() {}
Airac::~Airac() {
foreach (const QSet<Waypoint*> &wl, fixes) {
foreach (Waypoint* w, wl) {
delete w;
}
}
foreach (const QSet<NavAid*> &nl, navaids) {
foreach (NavAid* n, nl) {
delete n;
}
}
foreach (const QList<Airway*> &al, airways) {
foreach (Airway* a, al) {
delete a;
}
}
}
void Airac::load() {
qDebug() << Settings::navdataDirectory();
GuiMessages::status("Loading navigation database...", "airacload");
if (Settings::useNavdata()) {
readFixes(Settings::navdataDirectory());
readNavaids(Settings::navdataDirectory());
readAirways(Settings::navdataDirectory());
}
allPoints.clear();
allPoints.reserve(fixes.size() + navaids.size());
foreach (const QSet<Waypoint*> &wl, fixes.values()) {
foreach (Waypoint* w, wl) {
allPoints.insert(w);
}
}
foreach (const QSet<NavAid*> &nl, navaids.values()) {
foreach (NavAid* n, nl) {
allPoints.insert(n);
}
}
GuiMessages::remove("airacload");
emit loaded();
}
void Airac::readFixes(const QString& directory) {
fixes.clear();
const QString file(directory + "/earth_fix.dat");
FileReader fr(file);
// 1st line: just an "I"
fr.nextLine();
// 2nd line: navdata format version, build information and data source
const QString version = fr.nextLine();
if (version.left(2) != "11") {
qCritical() << file << "is not in X-Plane version 11 data format";
}
while (!fr.atEnd()) {
// file format:
// 49.862241667 9.348325000 SPESA ENRT ED 4530243
// https://developer.x-plane.com/article/navdata-in-x-plane-11/
QString line = fr.nextLine().trimmed();
if (line.isEmpty()) {
continue;
}
// 99 denotes EOF
if (line == "99") {
break;
}
Waypoint* wp = new Waypoint(line.split(' ', Qt::SkipEmptyParts));
if (wp == 0 || wp->id.isEmpty()) {
continue;
}
fixes[wp->id].insert(wp);
}
qDebug() << "Read fixes from" << (directory + "/earth_fix.dat")
<< "-" << fixes.size() << "imported";
}
void Airac::readNavaids(const QString& directory) {
navaids.clear();
const QString file(directory + "/earth_nav.dat");
FileReader fr(file);
// 1st line: just an "I"
fr.nextLine();
// 2nd line: navdata format version, build information and data source
const QString version = fr.nextLine();
if (version.left(2) != "11") {
qCritical() << file << "is not in X-Plane version 11 data format";
}
while (!fr.atEnd()) {
// file format:
// 3 52.721000000 -8.885222222 200 11330 130 -4.000 SHA ENRT EI SHANNON VOR/DME
// https://developer.x-plane.com/article/navdata-in-x-plane-11/
QString line = fr.nextLine().trimmed();
if (line.isEmpty()) {
continue;
}
// 99 denotes EOF
if (line == "99") {
break;
}
NavAid* nav = new NavAid(line.split(' ', Qt::SkipEmptyParts));
if (nav == 0 || nav->id.isEmpty()) {
continue;
}
// we only add those useful to us (for now)
if (
nav->type() == NavAid::Type::NDB || nav->type() == NavAid::Type::VOR
|| nav->type() == NavAid::Type::DME // yes, some airways actually use that
) {
navaids[nav->id].insert(nav);
} else if (nav->type() == NavAid::Type::DME_NO_FREQ) {
// upgrade VOR to VOR/DME - this assumes the DME_NO_FREQ line is always after the main VOR
foreach (auto* _n, navaids.value(nav->id)) {
if (_n->regionCode != nav->regionCode) {
continue;
}
_n->upgradeToVorDme();
}
}
}
qDebug() << "Read navaids from" << (directory + "/earth_nav.dat")
<< "-" << navaids.size() << "imported";
}
void Airac::readAirways(const QString& directory) {
// @todo: bring this in line with the other navdata source -> object converters
airways.clear();
const QString file(directory + "/earth_awy.dat");
FileReader fr(file);
// 1st line: just an "I"
fr.nextLine();
// 2nd line: navdata format version, build information and data source
const QString version = fr.nextLine();
if (version.left(2) != "11") {
qCritical() << file << "is not in X-Plane version 11 data format";
}
bool ok;
unsigned int count = 0;
int segments = 0;
while (!fr.atEnd()) {
++count;
QString line = fr.nextLine().trimmed();
// file format:
// EXOLU VA 11 TAXUN VA 11 N 2 75 460 B342-N519-W14
// https://developer.x-plane.com/article/navdata-in-x-plane-11/
if (line.isEmpty()) {
continue;
}
// 99 denotes EOF
if (line == "99") {
break;
}
QStringList list = line.split(' ', Qt::SkipEmptyParts);
if (list.size() != 11) {
QMessageLogger(file.toLocal8Bit(), count, QT_MESSAGELOG_FUNC).critical()
<< "not exactly 11 fields:" << list;
continue;
}
QString id = list[0];
QString regionCode = list[1];
int fixType = list[2].toInt(&ok);
if (!ok) {
QMessageLogger(file.toLocal8Bit(), count, QT_MESSAGELOG_FUNC).critical()
<< "unable to parse fix type (int):" << list;
continue;
}
Waypoint* start = waypoint(id, regionCode, fixType);
if (start == 0) {
QMessageLogger(file.toLocal8Bit(), count, QT_MESSAGELOG_FUNC).critical()
<< "unable to find start waypoint:" << QStringList{ id, regionCode, QString::number(fixType) } << list;
continue;
}
id = list[3];
regionCode = list[4];
fixType = list[5].toInt(&ok);
if (!ok) {
QMessageLogger(file.toLocal8Bit(), count, QT_MESSAGELOG_FUNC).critical()
<< "unable to parse fix type (int):" << list;
continue;
}
Waypoint* end = waypoint(id, regionCode, fixType);
if (end == 0) {
QMessageLogger(file.toLocal8Bit(), count, QT_MESSAGELOG_FUNC).critical()
<< "unable to find start waypoint:" << QStringList{ id, regionCode, QString::number(fixType) } << list;
continue;
}
QStringList names;
names = list[10].split('-', Qt::SkipEmptyParts);
for (int i = 0; i < names.size(); i++) {
addAirwaySegment(start, end, names[i]);
segments++;
}
}
QHash<QString, QList<Airway*> >::iterator iter;
for (iter = airways.begin(); iter != airways.end(); ++iter) {
QList<Airway*>& list = iter.value();
const QList<Airway*> sorted = list[0]->sort();
delete list[0];
list = sorted;
}
qDebug() << "Read airways from" << (directory + "/earth_awy.dat")
<< "-" << airways.size() << "airways," << segments << "segments imported and sorted";
}
Waypoint* Airac::waypoint(const QString &id, const QString ®ionCode, const int &type) const {
if (type == 11) {
foreach (Waypoint* w, fixes.value(id)) {
if (w->regionCode == regionCode) {
return w;
}
}
} else {
foreach (NavAid* n, navaids.value(id)) {
if (n->regionCode == regionCode) {
return n;
}
}
}
return nullptr;
}
/**
* find a waypoint that is near the given location with the given maximum distance.
* @returns 0 if none found
**/
Waypoint* Airac::waypointNearby(const QString& input, double lat, double lon, double maxDist = 20000.) {
// @todo clean this up
// @todo add "virtual" fixes (ARINC424) to our nav database upfront instead of returning them
// here dynamically (without adding them), which leads to duplicates
Waypoint* result = 0;
double minDist = 99999;
foreach (NavAid* n, navaids[input]) {
double d = NavData::distance(lat, lon, n->lat, n->lon);
if ((d < minDist) && (d < maxDist)) {
result = n;
minDist = d;
}
}
foreach (Waypoint* w, fixes[input]) {
double d = NavData::distance(lat, lon, w->lat, w->lon);
if ((d < minDist) && (d < maxDist)) {
result = w;
minDist = d;
}
}
if (NavData::instance()->airports.contains(input)) { // trying aerodromes
double d = NavData::distance(
lat, lon,
NavData::instance()->airports.value(input)->lat,
NavData::instance()->airports.value(input)->lon
);
if ((d < minDist) && (d < maxDist)) {
result = new Waypoint(
input, NavData::instance()->airports.value(input)->lat,
NavData::instance()->airports.value(input)->lon
);
minDist = d;
}
}
if (result == 0) { // trying generic formats
QRegExp eurocontrol("(\\d{2})"
"((\\d{2})?)"
"((\\d{2})?)"
"([NS])"
"(\\d{2,3})"
"((\\d{2})?)"
"((\\d{2})?)"
"([EW])"); // things that are valid for the Eurocontrol route validator:
// 63N005W or 6330N00530W (minutes) or 633000N0053000W (minutes and seconds)
// we are not strict and also allow 2-char longitudes like 63N05W
QRegExp slash("([\\-]?\\d{2})/([\\-]?\\d{2,3})"); // some pilots
// ..like to use non-standard: -53/170
double foundLat = -180., foundLon = -360.;
const QPair<double, double>* arincP = NavData::fromArinc(input);
if (arincP != 0) { // ARINC424
double d = NavData::distance(lat, lon, arincP->first, arincP->second);
if ((d < minDist) && (d < maxDist)) {
foundLat = arincP->first;
foundLon = arincP->second;
}
delete arincP;
} else if (eurocontrol.exactMatch(input)) {
auto capturedTexts = eurocontrol.capturedTexts();
double wLat = capturedTexts[1].toDouble() + capturedTexts[2].toDouble() / 60. + capturedTexts[4].toDouble() / 3600.;
double wLon = capturedTexts[7].toDouble() + capturedTexts[8].toDouble() / 60. + capturedTexts[10].toDouble() / 3600.;
if (capturedTexts[6] == "S") {
wLat = -wLat;
}
if (capturedTexts[12] == "W") {
wLon = -wLon;
}
double d = NavData::distance(lat, lon, wLat, wLon);
if ((d < minDist) && (d < maxDist)) {
foundLat = wLat;
foundLon = wLon;
}
} else if (slash.exactMatch(input)) { // slash-style: 35/30
auto capturedTexts = slash.capturedTexts();
double wLat = capturedTexts[1].toDouble();
double wLon = capturedTexts[2].toDouble();
double d = NavData::distance(lat, lon, wLat, wLon);
if ((d < minDist) && (d < maxDist)) {
foundLat = wLat;
foundLon = wLon;
}
}
if (foundLat > -180.) {
// try ARINC because some northern Atlantic waypoints are already in the AIRAC
QString foundId = NavData::toArinc(foundLat, foundLon);
if (foundId == "") {
foundId = NavData::toEurocontrol(foundLat, foundLon);
}
if (fixes.contains(foundId)) {
auto founds = fixes.value(foundId).values();
if (founds.size() > 0) {
return founds.at(0);
}
}
result = new Waypoint(foundId, foundLat, foundLon);
// we add it to our database
// @todo consider if this is a good idea here
fixes[foundId].insert(result);
}
}
return result;
}
Airway* Airac::airway(const QString& name) {
foreach (Airway* a, airways[name]) {
return a;
}
Airway* awy = new Airway(name);
airways[name].append(awy);
return awy;
}
Airway* Airac::airwayNearby(const QString& name, double lat, double lon) const {
const QList<Airway*> list = airways[name];
if (list.isEmpty()) {
return 0;
}
if (list.size() == 1) {
return list[0];
}
double minDist = 9999;
Airway* result = 0;
foreach (Airway* aw, list) {
Waypoint* wp = aw->closestPointTo(lat, lon);
if (wp == 0) {
continue;
}
double d = NavData::distance(lat, lon, wp->lat, wp->lon);
if (qFuzzyIsNull(d)) {
return aw;
}
if (d < minDist) {
minDist = d;
result = aw;
}
}
return result;
}
void Airac::addAirwaySegment(Waypoint* from, Waypoint* to, const QString& name) {
Airway* awy = airway(name);
awy->addSegment(from, to);
}
/**
* Returns a list of waypoints for the given planned route, starting at lat/lon.
* Airways along the route will be replaced by the appropriate fixes along that
* airway. lat/lon is being used as a hint and should be the position of the
* departure airport.
*
* Unknown fixes and/or airways will be ignored.
**/
QList<Waypoint*> Airac::resolveFlightplan(QStringList plan, double lat, double lon, double maxDist) {
QList<Waypoint*> result;
Waypoint* currPoint = 0;
Airway* awy = 0;
bool wantAirway = false;
while (!plan.isEmpty()) {
QString id = fpTokenToWaypoint(plan.takeFirst());
if (wantAirway) {
awy = airwayNearby(id, lat, lon);
}
if (wantAirway && (awy != 0) && !plan.isEmpty()) {
wantAirway = false;
// have airway - next should be a waypoint
QString endId = fpTokenToWaypoint(plan.first());
Waypoint* wp = waypointNearby(endId, lat, lon, maxDist);
if (wp != 0) {
if (currPoint != 0) {
auto _expand = awy->expand(currPoint->id, wp->id);
result.append(_expand);
}
currPoint = wp;
lat = wp->lat;
lon = wp->lon;
plan.removeFirst();
wantAirway = true;
}
} else if (awy == 0) {
if (!plan.isEmpty()) { // joining with the next point for idiot style..
if (
QRegExp("\\d{2,4}[NS]").exactMatch(id) //.. 30(00)N (0)50(00)W
&& QRegExp("(\\d{2,3}|\\d{5})[EW]").exactMatch(plan.first())
) {
id += fpTokenToWaypoint(plan.takeFirst());
}
}
Waypoint* wp = waypointNearby(id, lat, lon, maxDist);
if (wp != 0) {
result.append(wp);
currPoint = wp;
lat = wp->lat;
lon = wp->lon;
}
wantAirway = (wp != 0);
}
}
return result;
}
QString Airac::fpTokenToWaypoint(QString token) const {
// remove everything following an invalid character (e.g. "/N320F240", "/S1130K400")
return token.replace(QRegExp("[^A-Za-z0-9].*$"), "");
}
| 16,305
|
C++
|
.cpp
| 445
| 27.555056
| 129
| 0.541047
|
qutescoop/qutescoop
| 33
| 15
| 21
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,615
|
ClientSelectionWidget.cpp
|
qutescoop_qutescoop/src/ClientSelectionWidget.cpp
|
#include "ClientSelectionWidget.h"
ClientSelectionWidget::ClientSelectionWidget(QWidget* parent)
: QListWidget(parent) {
setWindowFlags(Qt::FramelessWindowHint);
setFocusPolicy(Qt::StrongFocus);
setFrameStyle(QFrame::NoFrame);
//setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
connect(this, &QListWidget::itemClicked, this, &ClientSelectionWidget::dialogForItem);
connect(this, &QListWidget::itemActivated, this, &ClientSelectionWidget::dialogForItem);
}
ClientSelectionWidget::~ClientSelectionWidget() {}
void ClientSelectionWidget::setObjects(QList<MapObject*> objects) {
clearObjects();
_displayClients = objects;
for (int i = 0; i < objects.size(); i++) {
addItem(objects[i]->toolTip());
}
setCurrentRow(0);
show();
resize(sizeHint());
raise();
setFocus();
}
void ClientSelectionWidget::clearObjects() {
clear();
_displayClients.clear();
}
void ClientSelectionWidget::dialogForItem(QListWidgetItem* item) {
foreach (MapObject* m, _displayClients) {
if (item->text() == m->toolTip()) {
if (m->hasPrimaryAction()) {
m->primaryAction();
}
close();
return;
}
}
}
void ClientSelectionWidget::focusOutEvent(QFocusEvent* event) {
if (event->reason() != Qt::MouseFocusReason) {
close();
}
}
QSize ClientSelectionWidget::sizeHint() const {
return contentsSize();
}
| 1,576
|
C++
|
.cpp
| 48
| 27.604167
| 92
| 0.689678
|
qutescoop/qutescoop
| 33
| 15
| 21
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,616
|
LineReader.cpp
|
qutescoop_qutescoop/src/LineReader.cpp
|
#include "LineReader.h"
#include <QStringList>
const QList<QPair<double, double> >& LineReader::readLine() {
_currentLine.clear();
while (!atEnd()) {
QString line = nextLine();
if (line == "end" || line.isNull()) {
break;
}
if (line.isEmpty() || line.startsWith(";")) {
continue;
}
QStringList list = line.split(':');
if (list.size() != 2) {
continue;
}
bool ok = true;
double lat = list[0].toDouble(&ok);
if (!ok) {
qWarning() << "unable to read lat (double):" << list;
continue;
}
double lon = list[1].toDouble(&ok);
if (!ok) {
qWarning() << "unable to read lon (double):" << list;
continue;
}
_currentLine.append(QPair<double, double>(lat, lon));
}
return _currentLine;
}
| 909
|
C++
|
.cpp
| 31
| 20.774194
| 65
| 0.49656
|
qutescoop/qutescoop
| 33
| 15
| 21
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,617
|
SearchVisitor.cpp
|
qutescoop_qutescoop/src/SearchVisitor.cpp
|
#include "SearchVisitor.h"
SearchVisitor::SearchVisitor(const QString& searchStr) {
// @todo this tries to cater for both ways (wildcards and regexp) but it does a bad job at that.
QStringList tokens = QString(searchStr)
.replace(QRegExp("\\*"), ".*")
.split(QRegExp("[ \\,]+"), Qt::SkipEmptyParts);
if (tokens.size() == 1) {
_regex = QRegExp("^" + tokens.first() + ".*", Qt::CaseInsensitive);
return;
}
QString regExpStr = "^(" + tokens.first();
for (int i = 1; i < tokens.size(); i++) {
regExpStr += "|" + tokens[i];
}
regExpStr += ".*)";
_regex = QRegExp(regExpStr, Qt::CaseInsensitive);
}
void SearchVisitor::visit(MapObject* object) {
if (!object->matches(_regex)) {
return;
}
_resultFromVisitors.append(object);
}
QList<MapObject*> SearchVisitor::result() const {
QList<MapObject*> result(_resultFromVisitors);
// airlines - this is not using the visitor model
foreach (const Airline* _airline, airlines) {
if (_airline->code.contains(_regex) || _airline->name.contains(_regex) || _airline->callsign.contains(_regex)) {
// we make it into a MapObject, because that fits the results here well
MapObject* object = new MapObject(
_airline->label(),
_airline->toolTip()
);
result.append(object);
}
}
std::sort(
result.begin(),
result.end(),
[](const MapObject* a, const MapObject* b) {
// we had a crash here
return a->mapLabel() < b->mapLabel();
}
);
return result;
}
| 1,656
|
C++
|
.cpp
| 46
| 28.804348
| 120
| 0.58401
|
qutescoop/qutescoop
| 33
| 15
| 21
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,618
|
NavAid.cpp
|
qutescoop_qutescoop/src/NavAid.cpp
|
#include "NavAid.h"
const QHash<NavAid::Type, QString> NavAid::typeStrings = {
{ NDB, "NDB" },
{ VOR, "VOR" },
{ ILS_LOC, "ILS" },
{ LOC, "LOC" },
{ GS, "GS" },
{ OM, "OM" },
{ MM, "OM" },
{ IM, "IM" },
{ DME_NO_FREQ, "DME (no freq)" },
{ DME, "DME" },
{ FAP_GBAS, "FAP alignment point" },
{ GBAS_GND, "GBAS Ground station" },
{ GBAS_THR, "GBAS Threshold point" },
{ CUSTOM_VORDME, "VOR/DME" }
};
NavAid::NavAid(const QStringList&stringList) {
if (stringList.size() < 12) {
QMessageLogger("earth_nav.dat", 0, QT_MESSAGELOG_FUNC).critical()
<< "could not parse" << stringList << "as Navaid. Expected more than 12 fields.";
return;
}
bool ok;
_type = (Type) stringList[0].toInt(&ok);
if (!ok) {
QMessageLogger("earth_nav.dat", 0, QT_MESSAGELOG_FUNC).critical()
<< "unable to parse waypointtype (int):" << stringList;
return;
}
lat = stringList[1].toDouble(&ok);
if (!ok) {
QMessageLogger("earth_nav.dat", 0, QT_MESSAGELOG_FUNC).critical()
<< "unable to parse lat (double):" << stringList;
return;
}
lon = stringList[2].toDouble(&ok);
if (!ok) {
QMessageLogger("earth_nav.dat", 0, QT_MESSAGELOG_FUNC).critical()
<< "unable to parse lon (double):" << stringList;
return;
}
_freq = stringList[4].toInt(&ok);
if (!ok) {
QMessageLogger("earth_nav.dat", 0, QT_MESSAGELOG_FUNC).critical()
<< "unable to parse freq (int):" << stringList;
return;
}
id = stringList[7];
regionCode = stringList[9];
_name = "";
for (int i = 10; i < stringList.size(); i++) {
_name += stringList[i] + (i > 9? " ": "");
}
_name = _name.trimmed();
}
QString NavAid::typeStr(Type type) {
return typeStrings.value(type, QString());
}
QString NavAid::toolTip() const {
QString ret = id + " (" + _name + ")";
if (_type == NDB) {
ret.append(QString(" %1 kHz").arg(_freq));
} else if (
_type == VOR || _type == DME || _type == DME_NO_FREQ
|| _type == ILS_LOC || _type == LOC || _type == GS
|| _type == CUSTOM_VORDME
) {
ret.append(QString(" %1 MHz").arg(_freq / 100., 0, 'f', 2));
} else if (_freq != 0) {
ret.append(QString(" %1?").arg(_freq));
}
if ((_type == ILS_LOC || _type == LOC) && _hdg != 0) {
ret.append(QString(" %1").arg((double) _hdg, 0, 'f', 0));
}
if (!NavAid::typeStr(_type).isEmpty()) {
ret.append(QString(" [%1]").arg(typeStr(_type)));
}
return ret;
}
QString NavAid::mapLabelHovered() const {
return (id + " " + typeStr(_type)).trimmed();
}
QStringList NavAid::mapLabelSecondaryLinesHovered() const {
QStringList ret = Waypoint::mapLabelSecondaryLinesHovered();
if (_name != id) {
ret << _name;
}
ret << freqString();
return ret;
}
QString NavAid::freqString() const {
if (_type == NDB) {
return QString("%1 kHz").arg(_freq);
} else if (
_type == VOR || _type == DME || _type == DME_NO_FREQ
|| _type == ILS_LOC || _type == LOC || _type == GS
|| _type == CUSTOM_VORDME
) {
return QString("%1 MHz").arg(_freq / 100., 0, 'f', 2);
}
return "";
}
int NavAid::type() {
return _type;
}
void NavAid::upgradeToVorDme() {
if (_type == VOR) {
_type = CUSTOM_VORDME;
}
}
| 3,468
|
C++
|
.cpp
| 111
| 25.477477
| 93
| 0.536228
|
qutescoop/qutescoop
| 33
| 15
| 21
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,619
|
Net.cpp
|
qutescoop_qutescoop/src/Net.cpp
|
#include "Net.h"
#include "Settings.h"
//Single instance
Net* netInstance = 0;
Net* Net::instance(bool createIfNoInstance) {
if ((netInstance == 0) && createIfNoInstance) {
netInstance = new Net();
}
return netInstance;
}
Net::Net()
: QNetworkAccessManager() {
if (Settings::useProxy()) {
setProxy(
QNetworkProxy(
QNetworkProxy::DefaultProxy, Settings::proxyServer(),
Settings::proxyPort(), Settings::proxyUser(),
Settings::proxyPassword()
)
);
}
}
QNetworkReply* Net::h(QNetworkRequest &request) {
request.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy);
return Net::instance()->head(request);
}
QNetworkReply* Net::g(const QUrl &url) {
QNetworkRequest request(url);
request.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy);
return Net::instance()->get(request);
}
QNetworkReply* Net::g(QNetworkRequest &request) {
request.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy);
return Net::instance()->get(request);
}
QNetworkReply* Net::p(QNetworkRequest &request, QIODevice* data) {
request.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy);
return Net::instance()->post(request, data);
}
QNetworkReply* Net::p(QNetworkRequest &request, const QByteArray &data) {
request.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy);
return Net::instance()->post(request, data);
}
| 1,683
|
C++
|
.cpp
| 43
| 34.139535
| 110
| 0.729779
|
qutescoop/qutescoop
| 33
| 15
| 21
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,620
|
MapObject.cpp
|
qutescoop_qutescoop/src/MapObject.cpp
|
#include "MapObject.h"
MapObject::MapObject()
: QObject(),
lat(0.),
lon(0.),
drawLabel(true),
m_label(QString()),
m_toolTip(QString()) {}
MapObject::MapObject(QString label, QString toolTip)
: QObject(),
lat(0.),
lon(0.),
drawLabel(true),
m_label(label),
m_toolTip(toolTip) {}
MapObject::MapObject(const MapObject& obj)
: QObject() {
if (this == &obj) {
return;
}
lat = obj.lat;
lon = obj.lon;
m_label = obj.m_label;
m_toolTip = obj.m_toolTip;
drawLabel = obj.drawLabel;
}
MapObject& MapObject::operator=(const MapObject& obj) {
if (this == &obj) {
return *this;
}
lat = obj.lat;
lon = obj.lon;
m_label = obj.m_label;
drawLabel = obj.drawLabel;
return *this;
}
MapObject::~MapObject() {}
// todo move into TextSearchable interface
bool MapObject::matches(const QRegExp ®ex) const {
return m_label.contains(regex)
|| mapLabel().contains(regex)
;
}
QString MapObject::mapLabel() const {
return m_label;
}
QString MapObject::mapLabelHovered() const {
return mapLabel();
}
QStringList MapObject::mapLabelSecondaryLines() const {
return {};
}
QStringList MapObject::mapLabelSecondaryLinesHovered() const {
return mapLabelSecondaryLines();
}
QString MapObject::toolTip() const {
return m_toolTip;
}
bool MapObject::hasPrimaryAction() const {
return false;
}
void MapObject::primaryAction() {}
| 1,489
|
C++
|
.cpp
| 62
| 19.806452
| 62
| 0.655099
|
qutescoop/qutescoop
| 33
| 15
| 21
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,621
|
Launcher.cpp
|
qutescoop_qutescoop/src/Launcher.cpp
|
#include "Airac.h"
#include "GuiMessage.h"
#include "JobList.h"
#include "Launcher.h"
#include "NavData.h"
#include "Net.h"
#include "Settings.h"
#include "Whazzup.h"
#include "dialogs/Window.h"
// singleton instance
Launcher* launcherInstance = 0;
Launcher* Launcher::instance(bool createIfNoInstance) {
if (launcherInstance == 0 && createIfNoInstance) {
launcherInstance = new Launcher();
}
return launcherInstance;
}
Launcher::Launcher(QWidget* parent)
: QWidget(parent,
Qt::SplashScreen | Qt::FramelessWindowHint | Qt::WindowSystemMenuHint) {
_map = QPixmap(":/startup/logo").scaled(600, 600);
resize(_map.width(), _map.height());
move(
qApp->primaryScreen()->availableGeometry().center()
- rect().center()
);
setMask(_map.mask());
_image = new QLabel(this);
_text = new QLabel(this);
_progress = new QProgressBar(this);
_image->setPixmap(_map);
_image->resize(_map.width(), _map.height());
_text->setText("Launcher started");
_text->setStyleSheet(
"QLabel {"
"color: white;"
"font-weight: bold;"
"}"
);
_text->setAlignment(Qt::AlignCenter);
_text->setWordWrap(true);
_text->resize(440, _text->height());
//qDebug() << "text frames w:" << text->frameSize() << " text h:" << text->height();
_text->move((_map.width() / 2) - 220, (_map.height() / 3) * 2 + 30);
_progress->hide();
_progress->setTextVisible(false);
_progress->resize(300, _progress->height());
_progress->move(
_map.width() / 2 - 150,
_map.height() / 3 * 2 + 30 + _text->height()
);
GuiMessages::instance()->addStatusLabel(_text);
GuiMessages::instance()->addProgressBar(_progress);
_image->lower();
_text->raise();
_progress->raise();
}
Launcher::~Launcher() {
delete _image;
delete _text;
}
///////////////////////////
// Events
///////////////////////////
void Launcher::mousePressEvent(QMouseEvent* event) {
if (event->button() == Qt::LeftButton) {
_dragPosition = event->globalPos() - frameGeometry().topLeft();
event->accept();
}
}
void Launcher::mouseMoveEvent(QMouseEvent* event) {
if (event->buttons() & Qt::LeftButton) {
move(event->globalPos() - _dragPosition);
event->accept();
}
}
///////////////////////////
// General
///////////////////////////
void Launcher::fireUp() {
qDebug() << "Launcher::fireUp()";
show();
JobList* jobs = new JobList(this);
// check for datafile updates
if (Settings::checkForUpdates()) {
jobs->append(
JobList::Job(
Launcher::instance(),
SLOT(checkData()), SIGNAL(dataChecked())
)
);
}
// load NavData
jobs->append(
JobList::Job(
NavData::instance(),
SLOT(load()), SIGNAL(loaded())
)
);
// load Airac
if (Settings::useNavdata()) {
jobs->append(
JobList::Job(
Airac::instance(),
SLOT(load()), SIGNAL(loaded())
)
);
}
// set up main window
jobs->append(
JobList::Job(
Window::instance(),
SLOT(restore()),
SIGNAL(restored())
)
);
if (Settings::downloadOnStartup()) {
jobs->append(
JobList::Job(
Whazzup::instance(),
SLOT(downloadJson3()),
SIGNAL(whazzupDownloaded())
)
);
}
connect(
jobs,
&JobList::finished,
this,
[this] {
GuiMessages::remove("joblist");
deleteLater();
}
);
jobs->start();
qDebug() << "Launcher::fireUp() finished";
}
///////////////////////////
//Navdata update & loading
///////////////////////////
void Launcher::checkData() {
qDebug() << "Launcher::checkData()";
GuiMessages::status("Checking for QuteScoop data file updates...", "checknavdata");
QUrl url(Settings::remoteDataRepository().arg("dataversions.txt"));
qDebug() << "checkForDataUpdates()" << url.toString();
_replyDataVersionsAndFiles = Net::g(url);
connect(_replyDataVersionsAndFiles, &QNetworkReply::finished, this, &Launcher::dataVersionsDownloaded);
}
void Launcher::dataVersionsDownloaded() {
qDebug() << "dataVersionsDownloaded()";
disconnect(_replyDataVersionsAndFiles, &QNetworkReply::finished, this, &Launcher::dataVersionsDownloaded);
_replyDataVersionsAndFiles->deleteLater();
if (_replyDataVersionsAndFiles->error() != QNetworkReply::NoError) {
GuiMessages::warning(_replyDataVersionsAndFiles->errorString());
GuiMessages::remove("checknavdata");
emit dataChecked();
}
_serverDataVersionsList.clear();
while (_replyDataVersionsAndFiles->canReadLine()) {
QStringList splitLine = QString(_replyDataVersionsAndFiles->readLine()).split("%%");
if (splitLine.count() != 2) {
continue;
}
_serverDataVersionsList[splitLine.first()] = splitLine.last().toInt();
}
qDebug() << "dataVersionsDownloaded() server:" << _serverDataVersionsList;
QFile localVersionsFile(Settings::dataDirectory("data/dataversions.txt"));
if (!localVersionsFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
GuiMessages::criticalUserInteraction(
QString("Could not read %1.\nThus we are updating all datafiles.")
.arg(localVersionsFile.fileName()),
"Complete datafiles update necessary"
);
}
_localDataVersionsList.clear();
while (!localVersionsFile.atEnd()) {
QStringList splitLine = QString(localVersionsFile.readLine()).split("%%");
if (splitLine.count() != 2) {
continue;
}
_localDataVersionsList[splitLine.first()] = splitLine.last().toInt();
}
qDebug() << "dataVersionsDownloaded() local: " << _localDataVersionsList;
localVersionsFile.close();
//collecting files to update
foreach (const QString fn, _serverDataVersionsList.keys()) {
// also download files that are locally not available
if (
!_localDataVersionsList.contains(fn)
|| _serverDataVersionsList[fn] > _localDataVersionsList[fn]
) {
_dataFilesToDownload.append(fn);
}
}
if (!_dataFilesToDownload.isEmpty()) {
GuiMessages::infoUserAttention(
"New sector data is available.\n"
"It will be downloaded now.",
"New datafiles"
);
QUrl url(Settings::remoteDataRepository()
.arg(_dataFilesToDownload.first()));
qDebug() << "dataVersionsDownloaded() Downloading datafile" << url.toString();
_replyDataVersionsAndFiles = Net::g(url);
connect(_replyDataVersionsAndFiles, &QNetworkReply::finished, this, &Launcher::dataFileDownloaded);
} else {
qDebug() << "dataVersionsDownloaded() all files up to date";
GuiMessages::remove("checknavdata");
emit dataChecked();
}
}
void Launcher::dataFileDownloaded() {
// processing received file
if (!_replyDataVersionsAndFiles->url().isEmpty()) {
qDebug() << "dataFileDownloaded() received"
<< _replyDataVersionsAndFiles->url();
disconnect(_replyDataVersionsAndFiles, &QNetworkReply::finished, this, &Launcher::dataFileDownloaded);
// error?
if (_replyDataVersionsAndFiles->error() != QNetworkReply::NoError) {
GuiMessages::criticalUserInteraction(
QString("Error downloading %1:\n%2")
.arg(_replyDataVersionsAndFiles->url().toString(), _replyDataVersionsAndFiles->errorString()),
"New datafiles"
);
} else {
// saving file
QFile f(Settings::dataDirectory("data/%1")
.arg(_dataFilesToDownload.first()));
qDebug() << "dataFileDownloaded() writing" << f.fileName();
if (f.open(QIODevice::WriteOnly)) {
f.write(_replyDataVersionsAndFiles->readAll());
f.flush();
f.close();
_localDataVersionsList[_dataFilesToDownload.first()] =
_serverDataVersionsList[_dataFilesToDownload.first()];
qDebug() << "dataFileDownloaded() updated" <<
_dataFilesToDownload.first() << "to version"
<< _localDataVersionsList[_dataFilesToDownload.first()];
GuiMessages::infoUserAttention(
QString("Downloaded %1")
.arg(_replyDataVersionsAndFiles->url().toString()),
"New datafiles"
);
} else {
GuiMessages::criticalUserInteraction(
QString("Error: Could not write to %1").arg(f.fileName()),
"New datafiles"
);
}
_dataFilesToDownload.removeFirst();
_replyDataVersionsAndFiles->deleteLater();
}
}
// starting new downloads
if (!_dataFilesToDownload.isEmpty()) {
QUrl url(Settings::remoteDataRepository()
.arg(_dataFilesToDownload.first()));
qDebug() << "dataVersionsDownloaded() Downloading datafile" << url.toString();
_replyDataVersionsAndFiles = Net::g(url);
connect(_replyDataVersionsAndFiles, &QNetworkReply::finished, this, &Launcher::dataFileDownloaded);
} else {
// we are finished
GuiMessages::infoUserAttention(
"New data has been downloaded.",
"New datafiles"
);
// updating local dataversions.txt
QFile localDataVersionsFile(Settings::dataDirectory("data/dataversions.txt"));
if (localDataVersionsFile.open(QIODevice::WriteOnly)) {
foreach (const QString fn, _localDataVersionsList.keys()) {
localDataVersionsFile.write(
QString("%1%%%2\n")
.arg(fn).arg(_localDataVersionsList[fn]).toLatin1()
);
}
localDataVersionsFile.close();
} else {
GuiMessages::criticalUserInteraction(
QString("Error writing %1").arg(localDataVersionsFile.fileName()),
"New datafiles"
);
}
GuiMessages::remove("checknavdata");
emit dataChecked();
}
}
void Launcher::loadNavdata() {
qDebug() << "Launcher:loadNavdata()";
GuiMessages::status("Loading Navdata", "loadnavdata");
NavData::instance()->load();
Airac::instance()->load();
GuiMessages::remove("loadnavdata");
qDebug() << "Launcher:loadNavdata() finished";
}
| 10,797
|
C++
|
.cpp
| 294
| 28.360544
| 110
| 0.590197
|
qutescoop/qutescoop
| 33
| 15
| 21
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,622
|
Airway.cpp
|
qutescoop_qutescoop/src/Airway.cpp
|
#include "Airway.h"
#include "NavData.h"
Airway::Segment::Segment(Waypoint* from, Waypoint* to) {
this->from = from;
this->to = to;
}
bool Airway::Segment::operator==(const Airway::Segment& other) const {
return (from == other.from || from == other.to)
&& (to == other.from || to == other.to);
}
Airway::Airway(const QString& name) {
this->name = name;
}
void Airway::addSegment(Waypoint* from, Waypoint* to) {
Segment newSegment(from, to);
// check if we already have this segment
for (int i = 0; i < _segments.size(); i++) {
if (_segments[i].from == newSegment.from && _segments[i].to == newSegment.to) {
return;
}
}
_segments.append(newSegment);
}
Airway* Airway::createFromSegments() {
if (_segments.isEmpty()) {
return 0;
}
Airway* result = new Airway(name);
Segment seg = _segments.first();
_segments.removeFirst();
result->_waypoints.append(seg.from);
result->_waypoints.append(seg.to);
bool nothingRemoved = false;
while (!_segments.isEmpty() && !nothingRemoved) {
nothingRemoved = true;
for (int i = 0; i < _segments.size() && nothingRemoved; i++) {
Segment s = _segments[i];
Waypoint* p = result->_waypoints.last();
if (s.from == p) {
result->_waypoints.append(s.to);
_segments.removeAt(i);
nothingRemoved = false;
continue;
}
if (s.to == p) {
result->_waypoints.append(s.from);
_segments.removeAt(i);
nothingRemoved = false;
continue;
}
p = result->_waypoints.first();
if (s.from == p) {
result->_waypoints.prepend(s.to);
_segments.removeAt(i);
nothingRemoved = false;
continue;
}
if (s.to == p) {
result->_waypoints.prepend(s.from);
_segments.removeAt(i);
nothingRemoved = false;
continue;
}
}
}
return result;
}
QList<Airway*> Airway::sort() {
QList<Airway*> result;
if (_segments.isEmpty()) {
return result;
}
Airway* awy = 0;
do {
awy = createFromSegments();
if (awy != 0) {
result.append(awy);
}
} while (awy != 0);
return result;
}
int Airway::index(const QString& id) const {
for (int i = 0; i < _waypoints.size(); i++) {
if (_waypoints[i]->id == id) {
return i;
}
}
return -1;
}
/**
* Returns a list of all fixes along this airway from start
* to end. The expanded list will not include the given start
* point, but will include the given end point.
*/
QList<Waypoint*> Airway::expand(const QString& startId, const QString& endId) const {
QList<Waypoint*> result;
int startIndex = index(startId);
int endIndex = index(endId);
if (startIndex < 0 || endIndex < 0) {
return result;
}
int direction = 1;
if (startIndex > endIndex) {
direction = -1;
}
for (int i = startIndex; i != endIndex; i += direction) {
if (i != startIndex) { // don't append first waypoint in list
result.append(_waypoints[i]);
}
}
result.append(_waypoints[endIndex]);
return result;
}
Waypoint* Airway::closestPointTo(double lat, double lon) const {
Waypoint* result = 0;
double minDist = 9999.;
for (int i = 0; i < _waypoints.size(); i++) {
double d = NavData::distance(lat, lon, _waypoints[i]->lat, _waypoints[i]->lon);
if (qFuzzyIsNull(d)) {
return _waypoints[i];
}
if (d < minDist) {
minDist = d;
result = _waypoints[i];
}
}
return result;
}
QList<Waypoint*> Airway::waypoints() const {
return _waypoints;
}
| 3,966
|
C++
|
.cpp
| 131
| 22.671756
| 87
| 0.54903
|
qutescoop/qutescoop
| 33
| 15
| 21
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,623
|
JobList.cpp
|
qutescoop_qutescoop/src/JobList.cpp
|
#include "GuiMessage.h"
#include "JobList.h"
JobList::JobList(QObject* parent)
: QObject(parent) {}
void JobList::append(JobList::Job job) {
m_jobs.append(job);
}
void JobList::start() {
for (int i = 0; i < m_jobs.size(); i++) {
connect(
m_jobs[i].obj,
m_jobs[i].finishSignal,
this,
SLOT(advanceProgress())
);
if (i + 1 < m_jobs.size()) {
m_jobs[i + 1].obj->connect(
m_jobs[i].obj,
m_jobs[i].finishSignal,
m_jobs[i + 1].start
);
} else {
connect(
m_jobs[i].obj,
m_jobs[i].finishSignal,
this,
SLOT(finish())
);
}
}
if (m_jobs.isEmpty()) {
connect(this, &JobList::started, this, &JobList::finish);
} else {
m_jobs[0].obj->connect(this, SIGNAL(started()), m_jobs[0].start);
}
GuiMessages::progress("joblist", m_progress, 100);
emit started();
}
void JobList::advanceProgress() {
if (m_jobs.isEmpty()) {
return;
}
m_progress += 100. / m_jobs.size();
GuiMessages::progress("joblist", m_progress, 100);
}
void JobList::finish() {
emit finished();
}
JobList::Job::Job(QObject* obj, const char* start, const char* finishSignal)
: obj(obj), start(start), finishSignal(finishSignal) {}
| 1,416
|
C++
|
.cpp
| 50
| 20.52
| 76
| 0.52651
|
qutescoop/qutescoop
| 33
| 15
| 21
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,624
|
WhazzupData.cpp
|
qutescoop_qutescoop/src/WhazzupData.cpp
|
#include "WhazzupData.h"
#include "Airport.h"
#include "BookedController.h"
#include "Controller.h"
#include "NavData.h"
#include "Pilot.h"
#include "Sector.h"
#include "Settings.h"
WhazzupData::WhazzupData()
: servers(QList<QStringList>()),
updateEarliest(QDateTime()), whazzupTime(QDateTime()), bookingsTime(QDateTime()),
_dataType(UNIFIED) {}
WhazzupData::WhazzupData(QByteArray* bytes, WhazzupType type)
: servers(QList<QStringList>()),
updateEarliest(QDateTime()), whazzupTime(QDateTime()),
bookingsTime(QDateTime()) {
qDebug() << type << "[NONE, WHAZZUP, ATCBOOKINGS, UNIFIED]";
_dataType = type;
int reloadInSec = Settings::downloadInterval();
QJsonDocument data = QJsonDocument::fromJson(*bytes);
if (data.isNull()) {
qDebug() << "Couldn't parse JSON";
} else if (type == WHAZZUP) {
QJsonObject json = data.object();
if (json.contains("general") && json["general"].isObject()) {
QJsonObject generalObject = json["general"].toObject();
if (generalObject.contains("update_timestamp") && generalObject["update_timestamp"].isString()) {
whazzupTime = QDateTime::fromString(generalObject["update_timestamp"].toString(), Qt::ISODate);
}
}
if (!whazzupTime.isValid()) {
// Assume it's the current time
whazzupTime = QDateTime::currentDateTime();
}
if (json.contains("servers") && json["servers"].isArray()) {
QJsonArray serversArray = json["servers"].toArray();
for (int i = 0; i < serversArray.size(); ++i) {
QJsonObject serverObject = serversArray[i].toObject();
if (
serverObject.contains("ident") && serverObject["ident"].isString()
&& serverObject.contains("hostname_or_ip") && serverObject["hostname_or_ip"].isString()
&& serverObject.contains("location") && serverObject["location"].isString()
&& serverObject.contains("name") && serverObject["name"].isString()
&& serverObject.contains("clients_connection_allowed") && serverObject["clients_connection_allowed"].isDouble()
) {
QStringList server;
server.append(serverObject["ident"].toString());
server.append(serverObject["hostname_or_ip"].toString());
server.append(serverObject["location"].toString());
server.append(serverObject["name"].toString());
server.append(serverObject["clients_connection_allowed"].toString());
servers += server;
}
}
}
if (json.contains("pilots") && json["pilots"].isArray()) {
QJsonArray pilotsArray = json["pilots"].toArray();
for (int i = 0; i < pilotsArray.size(); ++i) {
QJsonObject pilotObject = pilotsArray[i].toObject();
Pilot* p = new Pilot(pilotObject, this);
pilots[p->callsign] = p;
}
}
if (json.contains("controllers") && json["controllers"].isArray()) {
QJsonArray controllersArray = json["controllers"].toArray();
for (int i = 0; i < controllersArray.size(); ++i) {
QJsonObject controllerObject = controllersArray[i].toObject();
Controller* c = new Controller(controllerObject, this);
controllers[c->callsign] = c;
}
}
if (json.contains("atis") && json["atis"].isArray()) {
QJsonArray atisArray = json["atis"].toArray();
for (int i = 0; i < atisArray.size(); ++i) {
QJsonObject atisObject = atisArray[i].toObject();
Controller* c = new Controller(atisObject, this);
controllers[c->callsign] = c;
}
}
if (json.contains("prefiles") && json["prefiles"].isArray()) {
QJsonArray prefilesArray = json["prefiles"].toArray();
for (int i = 0; i < prefilesArray.size(); ++i) {
QJsonObject prefileObject = prefilesArray[i].toObject();
Pilot* p = new Pilot(prefileObject, this);
// currently not possible. Logic relies on lat=0, lon=0 for prefiles
// auto* a = p->depAirport();
// if (a != 0) {
// p->lat = a->lat;
// p->lon = a->lon;
// }
bookedPilots[p->callsign] = p;
}
}
// It looks like these were meant to be used as a bit mask but the IDs were chosen poorly
if (json.contains("ratings") && json["ratings"].isArray()) {
foreach (const auto rating, json["ratings"].toArray()) {
auto o = rating.toObject();
ratings.insert(o["id"].toInt(), o["short"].toString());
}
qDebug() << "ratings:" << ratings;
}
if (json.contains("pilot_ratings") && json["pilot_ratings"].isArray()) {
foreach (const auto rating, json["pilot_ratings"].toArray()) {
auto o = rating.toObject();
pilotRatings.insert(o["id"].toInt(), o["short_name"].toString());
}
qDebug() << "pilotRatings:" << pilotRatings;
}
if (json.contains("military_ratings") && json["military_ratings"].isArray()) {
foreach (const auto rating, json["military_ratings"].toArray()) {
auto o = rating.toObject();
militaryRatings.insert(o["id"].toInt(), o["short_name"].toString());
}
qDebug() << "militaryRatings:" << militaryRatings;
}
} else if (type == ATCBOOKINGS) {
QJsonArray json = data.array();
for (int i = 0; i < json.size(); ++i) {
QJsonObject bookedControllerJson = json[i].toObject();
BookedController* bc = new BookedController(bookedControllerJson);
bookedControllers.append(bc);
}
bookingsTime = QDateTime::currentDateTime();
} else {
// Try again in 15 seconds
updateEarliest = QDateTime::currentDateTime().addSecs(15);
}
// set the earliest time the server will have new data
if (whazzupTime.isValid() && reloadInSec > 0) {
updateEarliest = whazzupTime.addSecs(reloadInSec).toUTC();
}
qDebug() << "-- finished";
}
// faking WhazzupData based on valid data and a predictTime
WhazzupData::WhazzupData(const QDateTime predictTime, const WhazzupData &data)
: servers(QList<QStringList>()),
updateEarliest(QDateTime()), whazzupTime(QDateTime()),
bookingsTime(QDateTime()), predictionBasedOnTime(QDateTime()),
predictionBasedOnBookingsTime(QDateTime()) {
qDebug() << predictTime;
whazzupTime = predictTime;
predictionBasedOnTime = QDateTime(data.whazzupTime);
predictionBasedOnBookingsTime = QDateTime(data.bookingsTime);
if (!data.ratings.empty()) {
ratings = data.ratings;
}
if (!data.pilotRatings.empty()) {
pilotRatings = data.pilotRatings;
}
if (!data.militaryRatings.empty()) {
militaryRatings = data.militaryRatings;
}
_dataType = data._dataType;
// so now lets fake some controllers
foreach (const BookedController* bc, data.bookedControllers) {
// only ones booked for the selected time
if (bc->starts() <= predictTime && bc->ends() >= predictTime) {
QJsonObject controllerObject;
controllerObject["callsign"] = bc->callsign;
controllerObject["name"] = bc->realName();
controllerObject["cid"] = bc->userId.toInt();
controllerObject["facility"] = bc->facilityType;
controllerObject["rating"] = -99; // strictly out of API range
controllerObject["frequency"] = "?"; // cannot be empty
QJsonArray atisLines;
atisLines.append(
QString("BOOKED from %1, online until %2")
.arg(bc->starts().toString("HHmm'z'"), bc->ends().toString("HHmm'z'"))
);
atisLines.append(bc->bookingInfoStr);
controllerObject["text_atis"] = atisLines;
controllerObject["logon_time"] = bc->timeConnected.toString(Qt::ISODate);
controllerObject["server"] = "BOOKED SESSION";
controllerObject["visual_range"] = 0;
controllers[bc->callsign] = new Controller(controllerObject, this);
}
}
qDebug() << "added" << controllers.size() << "bookedControllers as fake controllers";
// let controllers be in until he states in his Controller Info also if only found in Whazzup, not booked
foreach (const Controller* c, data.controllers) {
// standard for online controllers: 4 min
QDateTime showUntil = predictionBasedOnTime.addSecs(4 * 60);
if (c->assumeOnlineUntil.isValid()) {
// only if before stated leave-time
if (predictionBasedOnTime.secsTo(c->assumeOnlineUntil) >= 0) {
showUntil = c->assumeOnlineUntil;
}
}
if (predictTime <= showUntil && predictTime >= predictionBasedOnTime) {
controllers[c->callsign] = new Controller(*c);
}
}
QDateTime startTime, endTime = QDateTime();
double startLat, startLon, endLat, endLon = 0.;
int altitude = 0;
foreach (const Pilot* p, data.allPilots()) {
//if (p == 0) continue;
if (!p->eta().isValid()) {
continue; // no ETA, no prediction...
}
if (!p->etd().isValid() && predictTime < predictionBasedOnTime) {
continue; // no ETD, difficult prediction. Before the whazzupTime, no prediction...
}
if (p->destAirport() == 0) {
continue; // sorry, no magic available yet. Just let him fly the last heading until etaPlan()?
// Does not make
// sense
}
if (p->etd() > predictTime || p->eta() < predictTime) {
if (p->flightStatus() == Pilot::PREFILED && p->etd() > predictTime) { // we want prefiled before
// their
//departure as in non-Warped view
Pilot* np = new Pilot(*p);
np->whazzupTime = QDateTime(predictTime);
bookedPilots[np->callsign] = np; // just copy him over
continue;
}
continue; // not on the map on the selected time
}
if (p->flightStatus() == Pilot::PREFILED) {
// if we dont know where a prefiled comes from, no magic available
if (p->depAirport() == 0 || p->destAirport() == 0) {
continue;
}
startTime = p->etd();
startLat = p->depAirport()->lat;
startLon = p->depAirport()->lon;
endTime = p->eta();
endLat = p->destAirport()->lat;
endLon = p->destAirport()->lon;
} else {
startTime = data.whazzupTime;
startLat = p->lat;
startLon = p->lon;
endTime = p->eta();
endLat = p->destAirport()->lat;
endLon = p->destAirport()->lon;
}
// altitude
if (p->planAlt.toInt() != 0) {
altitude = p->defuckPlanAlt(p->planAlt);
}
// position
double fraction = (double) startTime.secsTo(predictTime)
/ startTime.secsTo(endTime);
QPair<double, double> pos = NavData::greatCircleFraction(
startLat, startLon,
endLat, endLon, fraction
);
double dist = NavData::distance(startLat, startLon, endLat, endLon);
double enrouteHrs = ((double) startTime.secsTo(endTime)) / 3600.0;
if (qFuzzyIsNull(enrouteHrs)) {
enrouteHrs = 0.1;
}
double groundspeed = dist / enrouteHrs;
double trueHeading = NavData::courseTo(pos.first, pos.second, endLat, endLon);
// create Pilot instance and assign values
Pilot* np = new Pilot(*p);
np->whazzupTime = QDateTime(predictTime);
np->lat = pos.first;
np->lon = pos.second;
np->altitude = altitude;
np->trueHeading = trueHeading;
np->groundspeed = (int) groundspeed;
pilots[np->callsign] = np;
}
qDebug() << "-- finished";
}
WhazzupData::WhazzupData(const WhazzupData &data) {
assignFrom(data);
}
WhazzupData::~WhazzupData() {
foreach (const QString s, pilots.keys()) {
delete pilots[s];
}
pilots.clear();
foreach (const QString s, bookedPilots.keys()) {
delete bookedPilots[s];
}
bookedPilots.clear();
foreach (const QString s, controllers.keys()) {
delete controllers[s];
}
controllers.clear();
foreach (const BookedController* bc, bookedControllers) {
delete bc;
}
bookedControllers.clear();
}
WhazzupData &WhazzupData::operator=(const WhazzupData &data) {
assignFrom(data);
return *this;
}
bool WhazzupData::isNull() const {
return whazzupTime.isNull() && bookingsTime.isNull();
}
void WhazzupData::assignFrom(const WhazzupData &data) {
qDebug();
if (this == &data) {
return;
}
if (!data.ratings.empty()) {
ratings = data.ratings;
}
if (!data.pilotRatings.empty()) {
pilotRatings = data.pilotRatings;
}
if (!data.militaryRatings.empty()) {
militaryRatings = data.militaryRatings;
}
if (data._dataType == WHAZZUP || data._dataType == UNIFIED) {
if (_dataType == ATCBOOKINGS) {
_dataType = UNIFIED;
}
servers = data.servers;
whazzupTime = data.whazzupTime;
predictionBasedOnTime = data.predictionBasedOnTime;
updateEarliest = data.updateEarliest;
pilots.clear();
foreach (const QString s, data.pilots.keys()) {
pilots[s] = new Pilot(*data.pilots[s]);
}
bookedPilots.clear();
foreach (const QString s, data.bookedPilots.keys()) {
bookedPilots[s] = new Pilot(*data.bookedPilots[s]);
}
controllers.clear();
foreach (const QString s, data.controllers.keys()) {
controllers[s] = new Controller(*data.controllers[s]);
}
}
if (data._dataType == ATCBOOKINGS || data._dataType == UNIFIED) {
if (_dataType == WHAZZUP) {
_dataType = UNIFIED;
}
bookedControllers.clear();
foreach (const BookedController* bc, data.bookedControllers) {
bookedControllers.append(new BookedController(*bc));
}
bookingsTime = QDateTime(data.bookingsTime);
predictionBasedOnBookingsTime = QDateTime(data.predictionBasedOnBookingsTime);
}
qDebug() << "-- finished";
}
void WhazzupData::updatePilotsFrom(const WhazzupData &data) {
qDebug();
foreach (const QString s, pilots.keys()) { // remove pilots that are no longer there
if (!data.pilots.contains(s)) {
delete pilots.value(s);
pilots.remove(s);
}
}
foreach (const QString s, data.pilots.keys()) {
if (!pilots.contains(s)) { // new pilots
// create a new copy of new pilot
Pilot* p = new Pilot(*data.pilots[s]);
pilots[s] = p;
} else { // existing pilots: data saved in the object needs to be transferred
data.pilots[s]->showRoute = pilots[s]->showRoute;
data.pilots[s]->routeWaypointsCache = pilots[s]->routeWaypointsCache;
data.pilots[s]->routeWaypointsPlanDepCache = pilots[s]->routeWaypointsPlanDepCache;
data.pilots[s]->routeWaypointsPlanDestCache = pilots[s]->routeWaypointsPlanDestCache;
data.pilots[s]->routeWaypointsPlanRouteCache = pilots[s]->routeWaypointsPlanRouteCache;
data.pilots[s]->checkStatus();
*pilots[s] = *data.pilots[s];
}
}
foreach (const QString s, bookedPilots.keys()) { // remove pilots that are no longer there
if (!data.bookedPilots.contains(s)) {
delete bookedPilots.value(s);
bookedPilots.remove(s);
}
}
foreach (const QString s, data.bookedPilots.keys()) {
if (!bookedPilots.contains(s)) { // new pilots
Pilot* p = new Pilot(*data.bookedPilots[s]);
bookedPilots[s] = p;
} else { // existing pilots
*bookedPilots[s] = *data.bookedPilots[s];
}
}
qDebug() << "-- finished";
}
void WhazzupData::updateControllersFrom(const WhazzupData &data) {
qDebug();
foreach (const QString s, controllers.keys()) {
if (!data.controllers.contains(s)) {
// remove controllers that are no longer there
delete controllers[s];
controllers.remove(s);
}
}
foreach (const QString s, data.controllers.keys()) {
if (!controllers.contains(s)) {
// create a new copy of new controllers
Controller* c = new Controller(*data.controllers[s]);
controllers[c->callsign] = c;
} else { // controller already exists, assign values from data
*controllers[s] = *data.controllers[s];
}
}
qDebug() << "-- finished";
}
void WhazzupData::updateBookedControllersFrom(const WhazzupData &data) {
qDebug() << data.bookedControllers.size() << "bookedControllers";
bookedControllers.clear();
foreach (const BookedController* bc, data.bookedControllers) {
bookedControllers.append(new BookedController(*bc));
}
qDebug() << "-- finished";
}
void WhazzupData::updateFrom(const WhazzupData &data) {
qDebug();
if (this == &data) {
return;
}
if (data.isNull()) {
return;
}
if (!data.ratings.empty()) {
ratings = data.ratings;
}
if (!data.pilotRatings.empty()) {
pilotRatings = data.pilotRatings;
}
if (!data.militaryRatings.empty()) {
militaryRatings = data.militaryRatings;
}
if (data._dataType == WHAZZUP || data._dataType == UNIFIED) {
if (_dataType == ATCBOOKINGS) {
_dataType = UNIFIED;
}
updatePilotsFrom(data);
updateControllersFrom(data);
servers = data.servers;
whazzupTime = data.whazzupTime;
updateEarliest = data.updateEarliest;
predictionBasedOnTime = data.predictionBasedOnTime;
}
if (data._dataType == ATCBOOKINGS || data._dataType == UNIFIED) {
if (_dataType == WHAZZUP) {
_dataType = UNIFIED;
}
updateBookedControllersFrom(data);
bookingsTime = data.bookingsTime;
predictionBasedOnBookingsTime = data.predictionBasedOnBookingsTime;
}
qDebug() << "-- finished";
}
QSet<Controller*> WhazzupData::controllersWithSectors() const {
QSet<Controller*> result;
foreach (Controller* c, controllers.values()) {
if (c->sector != 0) {
result.insert(c);
}
}
return result;
}
QList<Pilot*> WhazzupData::allPilots() const {
return bookedPilots.values() + pilots.values();
}
QList<QPair<double, double> > WhazzupData::friendsLatLon() const {
QStringList friends = Settings::friends();
QList<QPair<double, double> > result;
foreach (Controller* c, controllers.values()) {
if (c->isAtis()) {
continue;
}
if (friends.contains(c->userId)) {
result.append(QPair<double, double>(c->lat, c->lon));
}
}
foreach (Pilot* p, pilots.values()) {
if (friends.contains(p->userId)) {
result.append(QPair<double, double>(p->lat, p->lon));
}
}
return result;
}
void WhazzupData::accept(MapObjectVisitor* visitor) const {
foreach (Controller* c, controllers) {
visitor->visit(c);
}
foreach (Pilot* p, pilots) {
visitor->visit(p);
}
foreach (Pilot* b, bookedPilots) {
visitor->visit(b);
}
}
Pilot* WhazzupData::findPilot(const QString &callsign) const {
Pilot* pilot = pilots.value(callsign);
if (pilot != 0) {
return pilot;
}
return bookedPilots.value(callsign, 0);
}
| 20,404
|
C++
|
.cpp
| 497
| 31.806841
| 131
| 0.587533
|
qutescoop/qutescoop
| 33
| 15
| 21
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,625
|
Sector.cpp
|
qutescoop_qutescoop/src/Sector.cpp
|
#include "Sector.h"
#include "helpers.h"
#include "Settings.h"
#include "Tessellator.h"
Sector::Sector(const QStringList &fields, const int debugControllerLineNumber, const int debugSectorLineNumber)
: _debugControllerLineNumber(debugControllerLineNumber),
_debugSectorLineNumber(debugSectorLineNumber),
_polygon(0), _borderline(0), _polygonHighlighted(0), _borderlineHighlighted(0) {
// LSAZ:Zurich::::189[:CTR]
if (fields.size() != 6 && fields.size() != 7) {
QMessageLogger("firlist.dat", debugControllerLineNumber, QT_MESSAGELOG_FUNC).critical()
<< fields << ": Expected 6-7 fields";
exit(EXIT_FAILURE);
}
icao = fields[0];
name = fields[1];
id = fields[5];
if (fields.size() >= 7) {
m_controllerSuffixes = fields[6].split(" ", Qt::SkipEmptyParts);
}
}
Sector::~Sector() {
if (_polygon != 0 && glIsList(_polygon) == GL_TRUE) {
glDeleteLists(_polygon, 1);
}
if (_borderline != 0 && glIsList(_borderline) == GL_TRUE) {
glDeleteLists(_borderline, 1);
}
if (_polygonHighlighted != 0 && glIsList(_polygonHighlighted) == GL_TRUE) {
glDeleteLists(_polygonHighlighted, 1);
}
if (_borderlineHighlighted != 0 && glIsList(_borderlineHighlighted) == GL_TRUE) {
glDeleteLists(_borderlineHighlighted, 1);
}
}
bool Sector::isNull() const {
return icao.isNull();
}
const QList<QPair<double, double> > &Sector::points() const {
return m_points;
}
bool Sector::containsPoint(const QPointF &pt) const {
foreach (const auto polygon, nonWrappedPolygons()) {
if (polygon.containsPoint(pt, Qt::OddEvenFill)) {
return true;
}
}
return false;
}
/**
* This contains 2 polygons where 1 can be empty.
* If this sector wraps at the longitude +/-180, this returns this sector split
* at the lon=-/+180 meridian.
* They are suitable to check for containment of a point.
*/
const QList<QPolygonF> &Sector::nonWrappedPolygons() const {
return m_nonWrappedPolygons;
}
void Sector::setPoints(const QList<QPair<double, double> > &points) {
m_points = points;
// Populate m_nonWrappedPolygons:
m_nonWrappedPolygons = { QPolygonF(), QPolygonF() };
bool iCurrentPolygon = 0;
auto currentPolygon = &m_nonWrappedPolygons[iCurrentPolygon];
const int count = m_points.size();
for (int i = 0; i < count; i++) {
auto current = m_points[i];
auto next = m_points[(i + 1) % count];
currentPolygon->append(QPointF(current.first, current.second));
// Lon +/-180 wrap
auto diff = std::abs(next.second - current.second);
if (diff > 180.) {
// add supporting point at the border to both sub-polygons
float latAtBorder = 0.;
float t;
if (current.second > 90.) {
auto diffCurrent = 180. - current.second;
auto diffNext = 180. + next.second;
auto total = diffCurrent + diffNext;
if (qFuzzyIsNull(total)) {
t = 0.;
} else {
t = diffCurrent / total;
}
latAtBorder = Helpers::lerp(current.first, next.first, t);
currentPolygon->append(QPointF(latAtBorder, 180.));
} else { // < -90.
auto diffCurrent = 180. + current.second;
auto diffNext = 180. - next.second;
auto total = diffCurrent + diffNext;
if (qFuzzyIsNull(total)) {
t = 0.;
} else {
t = diffCurrent / total;
}
latAtBorder = Helpers::lerp(current.first, next.first, t);
currentPolygon->append(QPointF(latAtBorder, -180.));
}
iCurrentPolygon = !iCurrentPolygon;
currentPolygon = &m_nonWrappedPolygons[iCurrentPolygon];
if (current.second > 90.) {
currentPolygon->append(QPointF(latAtBorder, -180.));
} else {
currentPolygon->append(QPointF(latAtBorder, 180.));
}
}
}
}
int Sector::debugControllerLineNumber() {
return _debugControllerLineNumber;
}
int Sector::debugSectorLineNumber() {
return _debugSectorLineNumber;
}
GLuint Sector::glPolygon() {
if (_polygon != 0 && glIsList(_polygon) == GL_TRUE) {
return _polygon;
}
_polygon = glGenLists(1);
glNewList(_polygon, GL_COMPILE);
QColor color = Settings::firFillColor();
glColor4f(color.redF(), color.greenF(), color.blueF(), color.alphaF());
Tessellator().tessellate(m_points);
glEndList();
return _polygon;
}
GLuint Sector::glBorderLine() {
if (_borderline != 0 && glIsList(_borderline) == GL_TRUE) {
return _borderline;
}
_borderline = glGenLists(1);
glNewList(_borderline, GL_COMPILE);
glLineWidth(Settings::firBorderLineStrength());
glBegin(GL_LINE_LOOP);
QColor color = Settings::firBorderLineColor();
glColor4f(color.redF(), color.greenF(), color.blueF(), color.alphaF());
for (int i = 0; i < m_points.size(); i++) {
VERTEXhigh(m_points[i].first, m_points[i].second);
}
glEnd();
glEndList();
return _borderline;
}
GLuint Sector::glPolygonHighlighted() {
if (_polygonHighlighted != 0 && glIsList(_polygonHighlighted) == GL_TRUE) {
return _polygonHighlighted;
}
_polygonHighlighted = glGenLists(1);
glNewList(_polygonHighlighted, GL_COMPILE);
QColor color = Settings::firHighlightedFillColor();
glColor4f(color.redF(), color.greenF(), color.blueF(), color.alphaF());
Tessellator().tessellate(m_points);
glEndList();
return _polygonHighlighted;
}
GLuint Sector::glBorderLineHighlighted() {
if (_borderlineHighlighted != 0 && glIsList(_borderlineHighlighted) == GL_TRUE) {
return _borderlineHighlighted;
}
// crashes here?!
_borderlineHighlighted = glGenLists(1);
glNewList(_borderlineHighlighted, GL_COMPILE);
glLineWidth(Settings::firHighlightedBorderLineStrength());
glBegin(GL_LINE_LOOP);
QColor color = Settings::firHighlightedBorderLineColor();
glColor4f(color.redF(), color.greenF(), color.blueF(), color.alphaF());
for (int i = 0; i < m_points.size(); i++) {
VERTEXhigh(m_points[i].first, m_points[i].second);
}
glEnd();
glEndList();
return _borderlineHighlighted;
}
QPair<double, double> Sector::getCenter() const {
return Helpers::polygonCenter(m_points);
}
const QStringList &Sector::controllerSuffixes() const {
return m_controllerSuffixes;
}
void Sector::setDebugSectorLineNumber(int newDebugSectorLineNumber) {
_debugSectorLineNumber = newDebugSectorLineNumber;
}
| 6,806
|
C++
|
.cpp
| 182
| 30.494505
| 111
| 0.632529
|
qutescoop/qutescoop
| 33
| 15
| 21
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,626
|
Settings.cpp
|
qutescoop_qutescoop/src/Settings.cpp
|
#include "Settings.h"
#include "GuiMessage.h"
#include "Whazzup.h"
#include "dialogs/AirportDetails.h"
#include "dialogs/ControllerDetails.h"
#include "dialogs/PilotDetails.h"
#include "dialogs/Window.h"
//singleton instance
QSettings* settingsInstance = 0;
QSettings* Settings::instance() {
if (settingsInstance == 0) {
settingsInstance = new QSettings();
if (Settings::resetOnNextStart()) {
settingsInstance->clear();
Settings::setResetOnNextStart(false);
}
migrate(settingsInstance);
}
return settingsInstance;
}
void Settings::migrate(QSettings* settingsInstance) {
struct Migration {
int version; // settings version this migrates to
const char* name;
std::function<void()> run;
};
const std::vector<Migration> migrations {
{
1,
"Whazzup status",
[settingsInstance]() {
if (
settingsInstance->value("download/network", 0).toInt() == 1
&& settingsInstance->value("download/statusLocation", "").toString() == "http://status.vatsim.net/"
) {
settingsInstance->setValue("download/network", 0);
qDebug() << "Found a user defined network, but VATSIM status location. Migrated.";
}
settingsInstance->remove("download/statusLocation");
}
},
{
2,
"Invalid aliases",
[settingsInstance]() {
settingsInstance->beginGroup("clients");
QStringList keys = settingsInstance->childKeys();
foreach (const auto key, keys) {
if (key.startsWith("alias_")) {
QString id = key.mid(6);
if (!Client::isValidID(id)) {
settingsInstance->remove(key);
qDebug() << "Found an alias for (invalid) client " << id << " and removed it. For more information see https://github.com/qutescoop/qutescoop/issues/130";
}
}
}
settingsInstance->endGroup();
QStringList friendList = settingsInstance->value("friends/friendList", QStringList()).toStringList();
foreach (const auto friendID, friendList) {
if (!Client::isValidID(friendID)) {
friendList.removeAt(friendList.indexOf(friendID));
qDebug() << "Found a friend list entry for (invalid) client " << friendID << " and removed it. For more information see https://github.com/qutescoop/qutescoop/issues/130";
}
}
settingsInstance->setValue("friends/friendList", friendList);
}
},
{
3,
"Bookings URL",
[settingsInstance]() {
const auto loc = settingsInstance->value("download/bookingsLocation").toString();
if (!loc.isEmpty() && loc != "http://vatbook.euroutepro.com/servinfo.asp") {
GuiMessages::criticalUserInteraction(
QString("You have set the location for bookings to %1.\nThis is different from the old default location. Due to an update in QuteScoop the old format for bookings is no longer supported.\n\nYou will be migrated to the new default VATSIM bookings URL.")
.arg(settingsInstance->value("download/bookingsLocation").toString()),
"Update of bookings format"
);
}
settingsInstance->setValue("download/bookingsLocation", "https://atc-bookings.vatsim.net/api/booking");
}
},
{
4,
"Removing typos in setting keys",
[settingsInstance]() {
const QList<QPair<QString, QString> > fromTos = {
{ "airportDisplay/dotSizer", "airportDisplay/dotSize" },
{ "airportDisplay/inactiveDotSizer", "airportDisplay/inactiveDotSize" },
{ "pilotDisplay/waypointsDotSizer", "pilotDisplay/waypointsDotSize" },
};
foreach (const auto fromTo, fromTos) {
if (settingsInstance->contains(fromTo.first)) {
settingsInstance->setValue(
fromTo.second,
settingsInstance->value(fromTo.first).value<double>()
);
qDebug() << "replaced" << fromTo.first << "with" << fromTo.second;
settingsInstance->remove(fromTo.first);
}
}
}
},
{
5,
"Remove obsolete settings",
[settingsInstance]() {
QList<QString> obsoleteSettings = {
"database/showAllWaypoints",
"screenshots/shootScreenshots",
"screenshots/method",
"screenshots/format",
"download/sendVersionInfo",
"download/updateVersionNumber",
"display/showALLSectors"
};
foreach (const auto setting, obsoleteSettings) {
settingsInstance->remove(setting);
}
}
},
{
6,
"Whazzup download interval is now seconds",
[settingsInstance]() {
settingsInstance->setValue(
"download/interval",
settingsInstance->value("download/interval", 1).value<int>() * 60
);
}
},
{
7,
"Adding more congestion options",
[settingsInstance]() {
// QColor
QList<QPair<QString, QString> > fromTos = {
{ "airportTraffic/borderLineColor", "airportTraffic/congestionColorMin" },
{ "airportTraffic/minimumMovements", "airportTraffic/congestionMovementsMin" },
{ "airportTraffic/borderLineStrength", "airportTraffic/borderLineStrengthMin" },
};
foreach (const auto fromTo, fromTos) {
if (settingsInstance->contains(fromTo.first)) {
settingsInstance->setValue(
fromTo.second,
settingsInstance->value(fromTo.first)
);
qDebug() << "replaced" << fromTo.first << "with" << fromTo.second;
settingsInstance->remove(fromTo.first);
}
}
}
},
};
foreach (const auto &migration, migrations) {
if (settingsInstance->value("settings/version", 0).toInt() < migration.version) {
qCritical() << QString("Migrating to settings version v%1: %2...").arg(migration.version).arg(migration.name);
migration.run();
settingsInstance->setValue("settings/version", migration.version);
}
}
}
/**
* path to .ini or Windows registry path (\HKEY_CURRENT_USER\Software\QuteScoop\QuteScoop)
*/
QString Settings::fileName() {
return instance()->fileName();
}
void Settings::exportToFile(QString fileName) {
QSettings* settings_file = new QSettings(fileName, QSettings::IniFormat);
QStringList settings_keys = instance()->allKeys();
foreach (const QString &key, instance()->allKeys()) {
settings_file->setValue(key, instance()->value(key));
}
delete settings_file;
}
void Settings::importFromFile(QString fileName) {
QSettings* settings_file = new QSettings(fileName, QSettings::IniFormat);
foreach (const QString &key, settings_file->allKeys()) {
instance()->setValue(key, settings_file->value(key));
}
delete settings_file;
}
/**
* @param composeFilePath path/file (/ is multi-platform, also on Win)
* @returns fully qualified path to the 'application data directory'.
**/
QString Settings::dataDirectory(const QString &composeFilePath) {
return QString("%1/%2")
.arg(QCoreApplication::applicationDirPath(), composeFilePath);
}
const QColor Settings::lightTextColor() {
auto _default = QGuiApplication::palette().text().color();
_default.setAlphaF(.5);
return instance()->value("display/lightTextColor", _default).value<QColor>();
}
int Settings::downloadInterval() {
return instance()->value("download/interval", 60).toInt();
}
void Settings::setDownloadInterval(int value) {
instance()->setValue("download/interval", value);
}
bool Settings::downloadOnStartup() {
// policy: see https://github.com/vatsimnetwork/developer-info/wiki/Data-Feeds-Live-Data
return instance()->value("download/downloadOnStartup", true).toBool();
}
void Settings::setDownloadOnStartup(bool value) {
instance()->setValue("download/downloadOnStartup", value);
}
bool Settings::downloadPeriodically() {
return instance()->value("download/downloadPeriodically", true).toBool();
}
void Settings::setDownloadPeriodically(bool value) {
instance()->setValue("download/downloadPeriodically", value);
}
bool Settings::downloadBookings() {
return instance()->value("download/downloadBookings", true).toBool();
}
void Settings::setDownloadBookings(bool value) {
instance()->setValue("download/downloadBookings", value);
}
QString Settings::bookingsLocation() {
return instance()->value("download/bookingsLocation", "http://vatbook.euroutepro.com/servinfo.asp").toString();
}
void Settings::setBookingsLocation(const QString& value) {
instance()->setValue("download/bookingsLocation", value);
}
bool Settings::bookingsPeriodically() {
return instance()->value("download/bookingsPeriodically", true).toBool();
}
void Settings::setBookingsPeriodically(bool value) {
instance()->setValue("download/bookingsPeriodically", value);
}
int Settings::bookingsInterval() {
return instance()->value("download/bookingsInterval", 30).toInt();
}
void Settings::setBookingsInterval(int value) {
instance()->setValue("download/bookingsInterval", value);
}
int Settings::downloadNetwork() {
return instance()->value("download/network", 0).toInt();
}
void Settings::setDownloadNetwork(int i) {
instance()->setValue("download/network", i);
Whazzup::instance()->setStatusLocation(statusLocation());
}
QString Settings::downloadNetworkName() {
switch (downloadNetwork()) {
case 0: return "VATSIM"; break;
case 1: return "User Network"; break;
}
return "Unknown";
}
QString Settings::userDownloadLocation() {
return instance()->value("download/userLocation", "http://www.network.org/status.txt").toString();
}
void Settings::setUserDownloadLocation(const QString& location) {
instance()->setValue("download/userLocation", location);
}
bool Settings::checkForUpdates() {
return instance()->value("download/checkForUpdates", true).toBool();
}
void Settings::setCheckForUpdates(bool value) {
instance()->setValue("download/checkForUpdates", value);
}
QString Settings::statusLocation() {
switch (downloadNetwork()) {
case 0: // VATSIM
return "https://status.vatsim.net/status.json";
case 1: // user defined
return userDownloadLocation();
}
return QString();
}
bool Settings::useProxy() {
return instance()->value("proxy/useProxy", false).toBool();
}
void Settings::setUseProxy(bool value) {
instance()->setValue("proxy/useProxy", value);
}
QString Settings::proxyServer() {
return instance()->value("proxy/server").toString();
}
void Settings::setProxyServer(const QString& server) {
instance()->setValue("proxy/server", server);
}
int Settings::proxyPort() {
return instance()->value("proxy/port", 8080).toInt();
}
void Settings::setProxyPort(int value) {
instance()->setValue("proxy/port", value);
}
QString Settings::proxyUser() {
return instance()->value("proxy/user").toString();
}
void Settings::setProxyUser(QString user) {
instance()->setValue("proxy/user", user);
}
QString Settings::proxyPassword() {
return instance()->value("proxy/password").toString();
}
void Settings::setProxyPassword(QString password) {
instance()->setValue("proxy/password", password);
}
QString Settings::navdataDirectory() {
return instance()->value("database/path").toString();
}
void Settings::setNavdataDirectory(const QString& directory) {
instance()->setValue("database/path", directory);
}
bool Settings::useNavdata() {
return instance()->value("database/use", false).toBool();
}
void Settings::setUseNavdata(bool value) {
instance()->setValue("database/use", value);
}
int Settings::metarDownloadInterval() {
return instance()->value("display/metarInterval", 1).toInt();
}
void Settings::setMetarDownloadInterval(int minutes) {
instance()->setValue("download/metarInterval", minutes);
}
//Display
bool Settings::showCTR() {
return instance()->value("display/showCTR", true).toBool();
}
void Settings::setShowCTR(bool value) {
instance()->setValue("display/showCTR", value);
}
bool Settings::showAPP() {
return instance()->value("display/showAPP", true).toBool();
}
void Settings::setShowAPP(bool value) {
return instance()->setValue("display/showAPP", value);
}
bool Settings::showTWR() {
return instance()->value("display/showTWR", true).toBool();
}
void Settings::setShowTWR(bool value) {
instance()->setValue("display/showTWR", value);
}
bool Settings::showGND() {
return instance()->value("display/showGND", true).toBool();
}
void Settings::setShowGND(bool value) {
instance()->setValue("display/showGND", value);
}
bool Settings::showRouteFix() {
return instance()->value("display/showRouteFix", false).toBool();
}
void Settings::setShowRouteFix(bool value) {
instance()->setValue("display/showRouteFix", value);
}
bool Settings::showPilotsLabels() {
return instance()->value("display/showPilotsLabels", true).toBool();
}
void Settings::setShowPilotsLabels(bool value) {
instance()->setValue("display/showPilotsLabels", value);
}
bool Settings::showInactiveAirports() {
return instance()->value("display/showInactive", true).toBool();
}
void Settings::setShowInactiveAirports(const bool& value) {
instance()->setValue("display/showInactive", value);
}
bool Settings::highlightFriends() {
return instance()->value("display/highlightFriends", false).toBool();
}
void Settings::setHighlightFriends(bool value) {
instance()->setValue("display/highlightFriends", value);
}
// OpenGL
bool Settings::showFps() {
return instance()->value("gl/showFps", false).toBool();
}
void Settings::setShowFps(bool value) {
instance()->setValue("gl/showFps", value);
}
bool Settings::displaySmoothLines() {
return instance()->value("gl/smoothLines", true).toBool();
}
void Settings::setDisplaySmoothLines(bool value) {
instance()->setValue("gl/smoothLines", value);
}
bool Settings::glStippleLines() {
return instance()->value("gl/stippleLines", true).toBool();
}
void Settings::setGlStippleLines(bool value) {
instance()->setValue("gl/stippleLines", value);
}
bool Settings::displaySmoothDots() {
return instance()->value("gl/smoothDots", true).toBool();
}
void Settings::setDisplaySmoothDots(bool value) {
instance()->setValue("gl/smoothDots", value);
}
int Settings::maxLabels() {
return instance()->value("gl/maxLabels", 130).toInt();
}
void Settings::setMaxLabels(int maxLabels) {
instance()->setValue("gl/maxLabels", maxLabels);
}
bool Settings::glBlending() {
return instance()->value("gl/blend", true).toBool();
}
void Settings::setGlBlending(bool value) {
instance()->setValue("gl/blend", value);
}
int Settings::glCirclePointEach() {
return instance()->value("gl/circlePointEach", 3).toInt();
}
void Settings::setGlCirclePointEach(int value) {
instance()->setValue("gl/circlePointEach", value);
}
bool Settings::glLighting() {
return instance()->value("gl/lighting", true).toBool();
}
void Settings::setEnableLighting(bool value) {
instance()->setValue("gl/lighting", value);
}
int Settings::glLights() {
return instance()->value("gl/lights", 6).toInt();
}
void Settings::setGlLights(int value) {
instance()->setValue("gl/lights", value);
}
int Settings::glLightsSpread() {
return instance()->value("gl/lightsSpread", 35).toInt();
}
void Settings::setGlLightsSpread(int value) {
instance()->setValue("gl/lightsSpread", value);
}
bool Settings::glTextures() {
return instance()->value("gl/earthTexture", true).toBool();
}
void Settings::setGlTextures(bool value) {
instance()->setValue("gl/earthTexture", value);
}
QString Settings::glTextureEarth() {
return instance()->value("gl/textureEarth", "4096px.png").toString();
}
void Settings::setGlTextureEarth(QString value) {
instance()->setValue("gl/textureEarth", value);
}
QColor Settings::sunLightColor() {
return instance()->value("gl/sunLightColor", QColor::fromRgb(70, 70, 70)).value<QColor>();
}
void Settings::setSunLightColor(const QColor& color) {
instance()->setValue("gl/sunLightColor", color);
}
QColor Settings::specularColor() {
return instance()->value("gl/sunSpecularColor", QColor::fromRgb(50, 22, 3)).value<QColor>();
}
void Settings::setSpecularColor(const QColor& color) {
instance()->setValue("gl/sunSpecularColor", color);
}
double Settings::earthShininess() {
return instance()->value("gl/earthShininess", 25).toDouble();
}
void Settings::setEarthShininess(double strength) {
instance()->setValue("gl/earthShininess", strength);
}
// Stylesheet
QString Settings::stylesheet() {
return instance()->value("display/stylesheet", QString()).toString();
}
void Settings::setStylesheet(const QString& value) {
instance()->setValue("display/stylesheet", value);
}
// earthspace
int Settings::earthGridEach() {
return instance()->value("earthSpace/earthGridEach", 30).toInt();
}
void Settings::setEarthGridEach(int value) {
instance()->setValue("earthSpace/earthGridEach", value);
}
QColor Settings::backgroundColor() {
return instance()->value("earthSpace/backgroundColor", QColor::fromRgbF(0, 0, 0)).value<QColor>();
}
void Settings::setBackgroundColor(const QColor& color) {
instance()->setValue("earthSpace/backgroundColor", color);
}
QColor Settings::globeColor() {
return instance()->value("earthSpace/globeColor", QColor::fromRgb(100, 100, 100)).value<QColor>();
}
void Settings::setGlobeColor(const QColor& color) {
instance()->setValue("earthSpace/globeColor", color);
}
QColor Settings::gridLineColor() {
return instance()->value("earthSpace/gridLineColor", QColor::fromRgb(100, 100, 100, 80)).value<QColor>();
}
void Settings::setGridLineColor(const QColor& color) {
instance()->setValue("earthSpace/gridLineColor", color);
}
double Settings::gridLineStrength() {
return instance()->value("earthSpace/gridLineStrength", 0.5).toDouble();
}
void Settings::setGridLineStrength(double strength) {
instance()->setValue("earthSpace/gridLineStrength", strength);
}
QColor Settings::countryLineColor() {
return instance()->value("earthSpace/countryLineColor", QColor::fromRgb(102, 85, 67, 150)).value<QColor>();
}
void Settings::setCountryLineColor(const QColor& color) {
instance()->setValue("earthSpace/countryLineColor", color);
}
double Settings::countryLineStrength() {
return instance()->value("earthSpace/countryLineStrength", 1.).toDouble();
}
void Settings::setCountryLineStrength(double strength) {
instance()->setValue("earthSpace/countryLineStrength", strength);
}
bool Settings::labelAlwaysBackdropped() {
return instance()->value("labels/alwaysShowBackdrop", false).toBool();
}
void Settings::setLabelAlwaysBackdropped(const bool v) {
instance()->setValue("labels/alwaysShowBackdrop", v);
}
QColor Settings::labelHoveredBgColor() {
return instance()->value("labelHover/labelHoveredBgColor", QColor::fromRgb(255, 255, 255, 190)).value<QColor>();
}
void Settings::setLabelHoveredBgColor(const QColor &color) {
instance()->setValue("labelHover/labelHoveredBgColor", color);
}
QColor Settings::labelHoveredBgDarkColor() {
return instance()->value("labelHover/labelHoveredBgDarkColor", QColor::fromRgb(0, 0, 0, 190)).value<QColor>();
}
void Settings::setLabelHoveredBgDarkColor(const QColor &color) {
instance()->setValue("labelHover/labelHoveredBgDarkColor", color);
}
bool Settings::showToolTips() {
return instance()->value("mapUi/showTooltips", false).toBool();
}
void Settings::setShowToolTips(const bool v) {
instance()->setValue("mapUi/showTooltips", v);
}
int Settings::hoverDebounceMs() {
return instance()->value("labelHover/debounceMs", 50).toInt();
}
void Settings::setHoverDebounceMs(int value) {
instance()->setValue("labelHover/debounceMs", value);
}
bool Settings::onlyShowHoveredLabels() {
return instance()->value("mapUi/onlyShowHoveredLabels", false).toBool();
}
void Settings::setOnlyShowHoveredLabels(const bool v) {
instance()->setValue("mapUi/onlyShowHoveredLabels", v);
}
QColor Settings::coastLineColor() {
return instance()->value("earthSpace/coastLineColor", QColor::fromRgb(102, 85, 67, 200)).value<QColor>();
}
void Settings::setCoastLineColor(const QColor& color) {
instance()->setValue("earthSpace/coastLineColor", color);
}
double Settings::coastLineStrength() {
return instance()->value("earthSpace/coastLineStrength", 2.).toDouble();
}
void Settings::setCoastLineStrength(double strength) {
instance()->setValue("earthSpace/coastLineStrength", strength);
}
// FIRs
QColor Settings::firBorderLineColor() {
return instance()->value("firDisplay/borderLineColor", QColor::fromRgb(42, 163, 214, 120)).value<QColor>();
}
void Settings::setFirBorderLineColor(const QColor& color) {
instance()->setValue("firDisplay/borderLineColor", color);
}
double Settings::firBorderLineStrength() {
return instance()->value("firDisplay/borderLineStrength", 1.5).toDouble();
}
void Settings::setFirBorderLineStrength(double strength) {
instance()->setValue("firDisplay/borderLineStrength", strength);
}
QColor Settings::firFontColor() {
return instance()->value("firDisplay/fontColor", QColor::fromRgb(170, 255, 255)).value<QColor>();
}
void Settings::setFirFontColor(const QColor& color) {
instance()->setValue("firDisplay/fontColor", color);
}
QFont Settings::firFont() {
QFont defaultFont;
defaultFont.setPointSize(13);
QFont result = instance()->value("firDisplay/font", defaultFont).value<QFont>();
result.setStyleHint(QFont::SansSerif, QFont::PreferAntialias);
return result;
}
void Settings::setFirFont(const QFont& font) {
instance()->setValue("firDisplay/font", font);
}
QColor Settings::firFontSecondaryColor() {
return instance()->value("firDisplay/fontSecondaryColor", firFontColor()).value<QColor>();
}
void Settings::setFirFontSecondaryColor(const QColor& color) {
instance()->setValue("firDisplay/fontSecondaryColor", color);
}
QFont Settings::firFontSecondary() {
QFont defaultFont = firFont();
if (defaultFont.pointSize() > -1) {
defaultFont.setPointSize(defaultFont.pointSize() - 1);
} else {
defaultFont.setPixelSize(defaultFont.pixelSize() - 1);
}
QFont result = instance()->value("firDisplay/fontSecondary", defaultFont).value<QFont>();
result.setStyleHint(QFont::SansSerif, QFont::PreferAntialias);
return result;
}
void Settings::setFirFontSecondary(const QFont& font) {
instance()->setValue("firDisplay/fontSecondary", font);
}
QColor Settings::firFillColor() {
return instance()->value("firDisplay/fillColor", QColor::fromRgb(42, 163, 214, 22)).value<QColor>();
}
void Settings::setFirFillColor(const QColor& color) {
instance()->setValue("firDisplay/fillColor", color);
}
QColor Settings::firHighlightedBorderLineColor() {
return instance()->value("firDisplay/borderLineColorHighlighted", QColor::fromRgb(200, 13, 214, 77)).value<QColor>();
}
void Settings::setFirHighlightedBorderLineColor(const QColor& color) {
instance()->setValue("firDisplay/borderLineColorHighlighted", color);
}
double Settings::firHighlightedBorderLineStrength() {
return instance()->value("firDisplay/borderLineStrengthHighlighted", 1.5).toDouble();
}
void Settings::setFirHighlightedBorderLineStrength(double strength) {
instance()->setValue("firDisplay/borderLineStrengthHighlighted", strength);
}
QColor Settings::firHighlightedFillColor() {
return instance()->value("firDisplay/fillColorHighlighted", QColor::fromRgb(200, 13, 214, 35)).value<QColor>();
}
void Settings::setFirHighlightedFillColor(const QColor& color) {
instance()->setValue("firDisplay/fillColorHighlighted", color);
}
QString Settings::firPrimaryContent() {
return instance()->value("firDisplay/primaryContent", "{sectorOrLogin}").toString();
}
void Settings::setFirPrimaryContent(const QString &value) {
instance()->setValue("firDisplay/primaryContent", value);
}
QString Settings::firPrimaryContentHovered() {
return instance()->value("firDisplay/primaryContentHovered", "{sectorOrLogin}").toString();
}
void Settings::setFirPrimaryContentHovered(const QString &value) {
instance()->setValue("firDisplay/primaryContentHovered", value);
}
QString Settings::firSecondaryContent() {
return instance()->value("firDisplay/secondaryContent", "{#cpdlc}@{cpdlc}{/cpdlc}{#livestream}📺{/livestream}").toString();
}
void Settings::setFirSecondaryContent(const QString &value) {
instance()->setValue("firDisplay/secondaryContent", value);
}
QString Settings::firSecondaryContentHovered() {
return instance()->value("firDisplay/secondaryContentHovered", "{#cpdlc}CPDLC@{cpdlc}{/cpdlc}\n{sector} {frequency}\n{name} {rating}\n{livestream}").toString();
}
void Settings::setFirSecondaryContentHovered(const QString &value) {
instance()->setValue("firDisplay/secondaryContentHovered", value);
}
//airport
QFont Settings::airportFont() {
QFont defaultResult;
defaultResult.setPointSize(9);
QFont result = instance()->value("airportDisplay/font", defaultResult).value<QFont>();
result.setStyleHint(QFont::SansSerif, QFont::PreferAntialias);
return result;
}
void Settings::setAirportFont(const QFont& font) {
instance()->setValue("airportDisplay/font", font);
}
QColor Settings::airportFontColor() {
return instance()->value("airportDisplay/fontColor", QColor::fromRgb(255, 255, 127, 200)).value<QColor>();
}
void Settings::setAirportFontColor(const QColor& color) {
instance()->setValue("airportDisplay/fontColor", color);
}
QFont Settings::airportFontSecondary() {
QFont defaultResult;
defaultResult.setPointSize(8);
QFont result = instance()->value("airportDisplay/fontSecondary", defaultResult).value<QFont>();
result.setStyleHint(QFont::SansSerif, QFont::PreferAntialias);
return result;
}
void Settings::setAirportFontSecondary(const QFont& font) {
instance()->setValue("airportDisplay/fontSecondary", font);
}
QColor Settings::airportFontSecondaryColor() {
return instance()->value("airportDisplay/fontSecondaryColor", QColor::fromRgb(255, 255, 255, 180)).value<QColor>();
}
void Settings::setAirportFontSecondaryColor(const QColor& color) {
instance()->setValue("airportDisplay/fontSecondaryColor", color);
}
QString Settings::airportPrimaryContent() {
return instance()->value("airportDisplay/primaryContent", "{code}{#pdc}@{/pdc} {> trafficArrows} {#livestream}📺{/livestream}").toString();
}
void Settings::setAirportPrimaryContent(const QString &value) {
instance()->setValue("airportDisplay/primaryContent", value);
}
QString Settings::airportPrimaryContentHovered() {
return instance()->value("airportDisplay/primaryContentHovered", "{code}{#pdc}@{/pdc} {> trafficArrows} {#livestream}📺{/livestream}").toString();
}
void Settings::setAirportPrimaryContentHovered(const QString &value) {
instance()->setValue("airportDisplay/primaryContentHovered", value);
}
QString Settings::airportSecondaryContent() {
return instance()->value("airportDisplay/secondaryContent", "").toString();
}
void Settings::setAirportSecondaryContent(const QString &value) {
instance()->setValue("airportDisplay/secondaryContent", value);
}
QString Settings::airportSecondaryContentHovered() {
return instance()->value("airportDisplay/secondaryContentHovered", "{prettyName}\n{#pdc}PDC@{pdc}{/pdc}\n{frequencies}\n{livestream}").toString();
}
void Settings::setAirportSecondaryContentHovered(const QString &value) {
instance()->setValue("airportDisplay/secondaryContentHovered", value);
}
QColor Settings::airportDotColor() {
return instance()->value("airportDisplay/dotColor", QColor::fromRgb(85, 170, 255, 150)).value<QColor>();
}
void Settings::setAirportDotColor(const QColor& color) {
instance()->setValue("airportDisplay/dotColor", color);
}
double Settings::airportDotSize() {
return instance()->value("airportDisplay/dotSize", 4).toDouble();
}
void Settings::setAirportDotSize(double value) {
instance()->setValue("airportDisplay/dotSize", value);
}
QColor Settings::inactiveAirportFontColor() {
return instance()->value("airportDisplay/inactiveFontColor", QColor::fromRgb(255, 255, 127, 100)).value<QColor>();
}
void Settings::setInactiveAirportFontColor(const QColor& color) {
instance()->setValue("airportDisplay/inactiveFontColor", color);
}
QColor Settings::inactiveAirportDotColor() {
return instance()->value("airportDisplay/inactiveDotColor", QColor::fromRgb(85, 170, 255, 50)).value<QColor>();
}
void Settings::setInactiveAirportDotColor(const QColor& color) {
instance()->setValue("airportDisplay/inactiveDotColor", color);
}
double Settings::inactiveAirportDotSize() {
return instance()->value("airportDisplay/inactiveDotSize", 2).toDouble();
}
void Settings::setInactiveAirportDotSize(double value) {
instance()->setValue("airportDisplay/inactiveDotSize", value);
}
QFont Settings::inactiveAirportFont() {
QFont defaultResult;
defaultResult.setPointSize(8);
QFont result = instance()->value("airportDisplay/inactiveFont", defaultResult).value<QFont>();
result.setStyleHint(QFont::SansSerif, QFont::PreferAntialias);
return result;
}
void Settings::setInactiveAirportFont(const QFont& font) {
instance()->setValue("airportDisplay/inactiveFont", font);
}
QColor Settings::twrBorderLineColor() {
return instance()->value("airportDisplay/twrBorderLineColor", appBorderLineColor()).value<QColor>();
}
void Settings::setTwrBorderLineColor(const QColor& color) {
instance()->setValue("airportDisplay/twrBorderLineColor", color);
}
double Settings::twrBorderLineWidth() {
return instance()->value("airportDisplay/twrBorderLineStrength", appBorderLineWidth()).toDouble();
}
void Settings::setTwrBorderLineStrength(double value) {
instance()->setValue("airportDisplay/twrBorderLineStrength", value);
}
QColor Settings::appBorderLineColor() {
return instance()->value("airportDisplay/appBorderLineColor", QColor::fromRgb(42, 163, 214, 80)).value<QColor>();
}
void Settings::setAppBorderLineColor(const QColor& color) {
instance()->setValue("airportDisplay/appBorderLineColor", color);
}
double Settings::appBorderLineWidth() {
return instance()->value("airportDisplay/appBorderLineStrength", 1.).toDouble();
}
void Settings::setAppBorderLineStrength(double value) {
instance()->setValue("airportDisplay/appBorderLineStrength", value);
}
QColor Settings::appCenterColor() {
return instance()->value("airportDisplay/appCenterColor", QColor::fromRgb(0, 0, 0, 0)).value<QColor>();
}
void Settings::setAppCenterColor(const QColor& color) {
instance()->setValue("airportDisplay/appCenterColor", color);
}
QColor Settings::appMarginColor() {
return instance()->value("airportDisplay/appMarginColor", QColor::fromRgb(34, 85, 99, 88)).value<QColor>();
}
void Settings::setAppMarginColor(const QColor& color) {
instance()->setValue("airportDisplay/appMarginColor", color);
}
QColor Settings::twrCenterColor() {
return instance()->value("airportDisplay/twrCenterColor", QColor::fromRgb(34, 85, 99, 10)).value<QColor>();
}
void Settings::setTwrCenterColor(const QColor& color) {
instance()->setValue("airportDisplay/twrCenterColor", color);
}
QColor Settings::twrMarginColor() {
return instance()->value("airportDisplay/twrMarginColor", QColor::fromRgb(144, 8, 255, 30)).value<QColor>();
}
void Settings::setTwrMarginColor(const QColor& color) {
instance()->setValue("airportDisplay/twrMarginColor", color);
}
QColor Settings::gndBorderLineColor() {
return instance()->value("airportDisplay/gndBorderLineColor", QColor::fromRgb(255, 255, 127, 40)).value<QColor>();
}
void Settings::setGndBorderLineColor(const QColor& color) {
instance()->setValue("airportDisplay/gndBorderLineColor", color);
}
double Settings::gndBorderLineWidth() {
return instance()->value("airportDisplay/gndBorderLineStrength", 1.0).toDouble();
}
void Settings::setGndBorderLineStrength(double value) {
instance()->setValue("airportDisplay/gndBorderLineStrength", value);
}
QColor Settings::gndFillColor() {
return instance()->value("airportDisplay/gndFillColor", QColor::fromRgb(12, 30, 35, 186)).value<QColor>();
}
void Settings::setGndFillColor(const QColor& color) {
instance()->setValue("airportDisplay/gndFillColor", color);
}
QColor Settings::delBorderLineColor() {
return instance()->value("airportDisplay/delBorderLineColor", gndBorderLineColor()).value<QColor>();
}
void Settings::setDelBorderLineColor(const QColor& color) {
instance()->setValue("airportDisplay/delBorderLineColor", color);
}
double Settings::delBorderLineWidth() {
return instance()->value("airportDisplay/delBorderLineStrength", gndBorderLineWidth()).toDouble();
}
void Settings::setDelBorderLineStrength(double value) {
instance()->setValue("airportDisplay/delBorderLineStrength", value);
}
QColor Settings::delFillColor() {
return instance()->value("airportDisplay/delFillColor", gndFillColor()).value<QColor>();
}
void Settings::setDelFillColor(const QColor& color) {
instance()->setValue("airportDisplay/delFillColor", color);
}
// Airport traffic
bool Settings::filterTraffic() {
return instance()->value("airportTraffic/filterTraffic", true).toBool();
}
void Settings::setFilterTraffic(bool v) {
instance()->setValue("airportTraffic/filterTraffic", v);
}
int Settings::filterDistance() {
return instance()->value("airportTraffic/filterDistance", 5).toInt();
}
void Settings::setFilterDistance(int v) {
instance()->setValue("airportTraffic/filterDistance", v);
}
double Settings::filterArriving() {
return instance()->value("airportTraffic/filterArriving", 1.0).toDouble();
}
void Settings::setFilterArriving(double v) {
instance()->setValue("airportTraffic/filterArriving", v);
}
// airport congestion
bool Settings::showAirportCongestion() {
return instance()->value("airportTraffic/showCongestion", true).toBool();
}
void Settings::setAirportCongestion(bool value) {
instance()->setValue("airportTraffic/showCongestion", value);
}
bool Settings::showAirportCongestionRing() {
return instance()->value("airportTraffic/showCongestionRing", false).toBool();
}
void Settings::setAirportCongestionRing(bool value) {
instance()->setValue("airportTraffic/showCongestionRing", value);
}
bool Settings::showAirportCongestionGlow() {
return instance()->value("airportTraffic/showCongestionGlow", true).toBool();
}
void Settings::setAirportCongestionGlow(bool value) {
instance()->setValue("airportTraffic/showCongestionGlow", value);
}
int Settings::airportCongestionMovementsMin() {
return instance()->value("airportTraffic/congestionMovementsMin", 10).toInt();
}
void Settings::setAirportCongestionMovementsMin(int value) {
instance()->setValue("airportTraffic/congestionMovementsMin", value);
}
int Settings::airportCongestionRadiusMin() {
return instance()->value("airportTraffic/congestionRadiusMin", 20).toInt();
}
void Settings::setAirportCongestionRadiusMin(int value) {
instance()->setValue("airportTraffic/congestionRadiusMin", value);
}
QColor Settings::airportCongestionColorMin() {
return instance()->value("airportTraffic/congestionColorMin", QColor::fromRgb(20, 100, 170, 60)).value<QColor>();
}
void Settings::setAirportCongestionColorMin(const QColor& color) {
instance()->setValue("airportTraffic/congestionColorMin", color);
}
double Settings::airportCongestionBorderLineStrengthMin() {
return instance()->value("airportTraffic/borderLineStrengthMin", 2).toDouble();
}
void Settings::setAirportCongestionBorderLineStrengthMin(double value) {
instance()->setValue("airportTraffic/borderLineStrengthMin", value);
}
int Settings::airportCongestionMovementsMax() {
return instance()->value("airportTraffic/congestionMovementsMax", 60).toInt();
}
void Settings::setAirportCongestionMovementsMax(int value) {
instance()->setValue("airportTraffic/congestionMovementsMax", value);
}
int Settings::airportCongestionRadiusMax() {
return instance()->value("airportTraffic/congestionRadiusMax", 100).toInt();
}
void Settings::setAirportCongestionRadiusMax(int value) {
instance()->setValue("airportTraffic/congestionRadiusMax", value);
}
QColor Settings::airportCongestionColorMax() {
return instance()->value("airportTraffic/congestionColorMax", QColor::fromRgb(20, 100, 170, 160)).value<QColor>();
}
void Settings::setAirportCongestionColorMax(const QColor& color) {
instance()->setValue("airportTraffic/congestionColorMax", color);
}
double Settings::airportCongestionBorderLineStrengthMax() {
return instance()->value("airportTraffic/borderLineStrengthMax", 6).toDouble();
}
void Settings::setAirportCongestionBorderLineStrengthMax(double value) {
instance()->setValue("airportTraffic/borderLineStrengthMax", value);
}
// pilot
QColor Settings::pilotFontColor() {
return instance()->value("pilotDisplay/fontColor", QColor::fromRgb(255, 0, 127)).value<QColor>();
}
void Settings::setPilotFontColor(const QColor& color) {
instance()->setValue("pilotDisplay/fontColor", color);
}
QFont Settings::pilotFont() {
QFont defaultFont;
defaultFont.setPointSize(8);
return instance()->value("pilotDisplay/font", defaultFont).value<QFont>();
}
void Settings::setPilotFont(const QFont& font) {
instance()->setValue("pilotDisplay/font", font);
}
QColor Settings::pilotFontSecondaryColor() {
return instance()->value("pilotDisplay/fontSecondaryColor", QColor::fromRgb(170, 255, 255, 180)).value<QColor>();
}
void Settings::setPilotFontSecondaryColor(const QColor &color) {
instance()->setValue("pilotDisplay/fontSecondaryColor", color);
}
QFont Settings::pilotFontSecondary() {
QFont defaultFont;
defaultFont.setPointSize(7);
return instance()->value("pilotDisplay/fontSecondary", defaultFont).value<QFont>();
}
void Settings::setPilotFontSecondary(const QFont &font) {
instance()->setValue("pilotDisplay/fontSecondary", font);
}
QString Settings::pilotPrimaryContent() {
return instance()->value("pilotDisplay/primaryContent", "{login} {rulesIfNotIfr}").toString();
}
void Settings::setPilotPrimaryContent(const QString &value) {
instance()->setValue("pilotDisplay/primaryContent", value);
}
QString Settings::pilotPrimaryContentHovered() {
return instance()->value("pilotDisplay/primaryContentHovered", "{login} {rulesIfNotIfr}").toString();
}
void Settings::setPilotPrimaryContentHovered(const QString &value) {
instance()->setValue("pilotDisplay/primaryContentHovered", value);
}
QString Settings::pilotSecondaryContent() {
return instance()->value("pilotDisplay/secondaryContent", "{rating} {#livestream}📺{/livestream}").toString();
}
void Settings::setPilotSecondaryContent(const QString &value) {
instance()->setValue("pilotDisplay/secondaryContent", value);
}
QString Settings::pilotSecondaryContentHovered() {
return instance()->value("pilotDisplay/secondaryContentHovered", "{FL} {GS10} {type}\n{dest}\n{livestream}").toString();
}
void Settings::setPilotSecondaryContentHovered(const QString &value) {
instance()->setValue("pilotDisplay/secondaryContentHovered", value);
}
QColor Settings::pilotDotColor() {
return instance()->value("pilotDisplay/dotColor", QColor::fromRgb(255, 0, 127, 100)).value<QColor>();
}
void Settings::setPilotDotColor(const QColor& color) {
instance()->setValue("pilotDisplay/dotColor", color);
}
double Settings::pilotDotSize() {
return instance()->value("pilotDisplay/dotSize", 3).toDouble();
}
void Settings::setPilotDotSize(double value) {
instance()->setValue("pilotDisplay/dotSize", value);
}
int Settings::timelineSeconds() {
return instance()->value("pilotDisplay/timelineSeconds", 120).toInt();
}
void Settings::setTimelineSeconds(int value) {
instance()->setValue("pilotDisplay/timelineSeconds", value);
}
QColor Settings::leaderLineColor() {
return instance()->value("pilotDisplay/timeLineColor", QColor::fromRgb(255, 0, 127, 80)).value<QColor>();
}
void Settings::setLeaderLineColor(const QColor& color) {
instance()->setValue("pilotDisplay/timeLineColor", color);
}
double Settings::timeLineStrength() {
return instance()->value("pilotDisplay/timeLineStrength", 1.).toDouble();
}
void Settings::setTimeLineStrength(double value) {
instance()->setValue("pilotDisplay/timeLineStrength", value);
}
// Waypoints
bool Settings::showUsedWaypoints() {
return instance()->value("display/showUsedWaypoints", false).toBool();
}
void Settings::setShowUsedWaypoints(bool value) {
instance()->setValue("display/showUsedWaypoints", value);
}
QColor Settings::waypointsFontColor() {
return instance()->value("pilotDisplay/waypointsFontColor", QColor::fromRgbF(.7, .7, .7, .7)).value<QColor>();
}
void Settings::setWaypointsFontColor(const QColor& color) {
instance()->setValue("pilotDisplay/waypointsFontColor", color);
}
QColor Settings::waypointsDotColor() {
return instance()->value("pilotDisplay/waypointsDotColor", QColor::fromRgbF(.8, .8, 0., .7)).value<QColor>();
}
void Settings::setWaypointsDotColor(const QColor& color) {
instance()->setValue("pilotDisplay/waypointsDotColor", color);
}
double Settings::waypointsDotSize() {
return instance()->value("pilotDisplay/waypointsDotSize", 2.).toDouble();
}
void Settings::setWaypointsDotSize(double value) {
instance()->setValue("pilotDisplay/waypointsDotSize", value);
}
QFont Settings::waypointsFont() {
QFont defaultResult;
defaultResult.setPointSize(8);
QFont result = instance()->value("pilotDisplay/waypointsFont", defaultResult).value<QFont>();
result.setStyleHint(QFont::SansSerif, QFont::PreferAntialias);
return result;
}
void Settings::setWaypointsFont(const QFont& font) {
instance()->setValue("pilotDisplay/waypointsFont", font);
}
// routes
bool Settings::showRoutes() {
return instance()->value("display/showRoutes", false).toBool();
}
void Settings::setShowRoutes(bool value) {
instance()->setValue("display/showRoutes", value);
}
bool Settings::onlyShowImmediateRoutePart() {
return instance()->value("display/onlyShowImmediateRoutePart", false).toBool();
}
void Settings::setOnlyShowImmediateRoutePart(bool value) {
instance()->setValue("display/onlyShowImmediateRoutePart", value);
}
QColor Settings::depLineColor() {
return instance()->value("pilotDisplay/depLineColor", QColor::fromRgb(170, 255, 127, 40)).value<QColor>();
}
void Settings::setDepLineColor(const QColor& color) {
instance()->setValue("pilotDisplay/depLineColor", color);
}
double Settings::depLineStrength() {
return instance()->value("pilotDisplay/depLineStrength", .8).toDouble();
}
void Settings::setDepLineStrength(double value) {
instance()->setValue("pilotDisplay/depLineStrength", value);
}
bool Settings::depLineDashed() {
return instance()->value("pilotDisplay/depLineDashed", true).toBool();
}
void Settings::setDepLineDashed(bool value) {
instance()->setValue("pilotDisplay/depLineDashed", value);
}
int Settings::destImmediateDurationMin() {
return instance()->value("pilotDisplay/destImmediateDurationMin", 30).toInt();
}
void Settings::setDestImmediateDurationMin(int value) {
instance()->setValue("pilotDisplay/destImmediateDurationMin", value);
}
QColor Settings::destImmediateLineColor() {
return instance()->value("pilotDisplay/destImmediateLineColor", QColor::fromRgb(255, 170, 0, 30)).value<QColor>();
}
void Settings::setDestImmediateLineColor(const QColor& color) {
instance()->setValue("pilotDisplay/destImmediateLineColor", color);
}
double Settings::destImmediateLineStrength() {
return instance()->value("pilotDisplay/destImmediateLineStrength", destLineStrength() * 3.).toDouble();
}
void Settings::setDestImmediateLineStrength(double value) {
instance()->setValue("pilotDisplay/destImmediateLineStrength", value);
}
QColor Settings::destLineColor() {
return instance()->value("pilotDisplay/destLineColor", QColor::fromRgb(255, 170, 0, 30)).value<QColor>();
}
void Settings::setDestLineColor(const QColor& color) {
instance()->setValue("pilotDisplay/destLineColor", color);
}
void Settings::setDestLineDashed(bool value) {
instance()->setValue("pilotDisplay/destLineDashed", value);
}
bool Settings::destLineDashed() {
return instance()->value("pilotDisplay/destLineDashed", false).toBool();
}
double Settings::destLineStrength() {
return instance()->value("pilotDisplay/destLineStrength", .8).toDouble();
}
void Settings::setDestLineStrength(double value) {
instance()->setValue("pilotDisplay/destLineStrength", value);
}
void Settings::rememberedMapPosition(
double* xrot,
double*, // unused yrot
double* zrot,
double* zoom,
int nr
) {
*xrot = instance()->value(
"defaultMapPosition/xrot" + QString("%1").arg(nr), -90.
).toDouble();
// ignore yRot: no Earth tilting
*zrot = instance()->value(
"defaultMapPosition/zrot" + QString("%1").arg(nr), 0.
).toDouble();
*zoom = instance()->value(
"defaultMapPosition/zoom" + QString("%1").arg(nr), 2.
).toDouble();
}
void Settings::setRememberedMapPosition(
double xrot,
double yrot,
double zrot,
double zoom,
int nr
) {
instance()->setValue(
"defaultMapPosition/xrot" + QString("%1").arg(nr), xrot
);
instance()->setValue(
"defaultMapPosition/yrot" + QString("%1").arg(nr), yrot
);
instance()->setValue(
"defaultMapPosition/zrot" + QString("%1").arg(nr), zrot
);
instance()->setValue(
"defaultMapPosition/zoom" + QString("%1").arg(nr), zoom
);
}
bool Settings::rememberMapPositionOnClose() {
return instance()->value("defaultMapPosition/rememberMapPositionOnClose", true).toBool();
}
void Settings::setRememberMapPositionOnClose(bool val) {
instance()->setValue("defaultMapPosition/rememberMapPositionOnClose", val);
}
// URL for data update checks; not in preferences
QString Settings::remoteDataRepository() {
return instance()->value(
"data/remoteDataRepository",
"https://raw.githubusercontent.com/qutescoop/qutescoop/master/data/%1"
)
.toString();
}
QColor Settings::friendsHighlightColor() {
return instance()->value("pilotDisplay/highlightColor", QColor::fromRgb(255, 255, 127, 180)).value<QColor>();
}
void Settings::setFriendsHighlightColor(QColor &color) {
instance()->setValue("pilotDisplay/highlightColor", color);
}
QColor Settings::friendsPilotDotColor() {
return instance()->value("friends/pilotDotColor", friendsHighlightColor()).value<QColor>();
}
QColor Settings::friendsAirportDotColor() {
return instance()->value("friends/airportDotColor", friendsHighlightColor()).value<QColor>();
}
QColor Settings::friendsPilotLabelRectColor() {
return instance()->value("friends/pilotLabelRectColor", friendsHighlightColor()).value<QColor>();
}
QColor Settings::friendsAirportLabelRectColor() {
return instance()->value("friends/airportLabelRectColor", friendsHighlightColor()).value<QColor>();
}
QColor Settings::friendsSectorLabelRectColor() {
return instance()->value("friends/sectorLabelRectColor", friendsHighlightColor()).value<QColor>();
}
double Settings::highlightLineWidth() {
return instance()->value("pilotDisplay/highlightLineWidth", 2.5).toDouble();
}
void Settings::setHighlightLineWidth(double value) {
instance()->setValue("pilotDisplay/highlightLineWidth", value);
}
bool Settings::animateFriendsHighlight() {
return instance()->value("pilotDisplay/useHighlightAnimation", false).toBool();
}
void Settings::setAnimateFriendsHighlight(bool value) {
instance()->setValue("pilotDisplay/useHighlightAnimation", value);
}
const QStringList Settings::friends() {
return instance()->value("friends/friendList", QStringList()).toStringList();
}
void Settings::addFriend(const QString& friendId) {
QStringList fl = friends();
if (!fl.contains(friendId)) {
fl.append(friendId);
}
instance()->setValue("friends/friendList", fl);
}
void Settings::removeFriend(const QString& friendId) {
QStringList fl = friends();
int i = fl.indexOf(friendId);
if (i >= 0 && i < fl.size()) {
fl.removeAt(i);
}
instance()->setValue("friends/friendList", fl);
}
const QString Settings::clientAlias(const QString &userId) {
return instance()->value(
QString("clients/alias_%1").arg(userId)
).toString();
}
void Settings::setClientAlias(const QString &userId, const QString &alias) {
if (alias.isEmpty()) {
instance()->remove(
QString("clients/alias_%1").arg(userId)
);
} else {
instance()->setValue(
QString("clients/alias_%1").arg(userId),
alias
);
}
// should maybe use signals instead
auto wnd = Window::instance(false);
if (wnd != 0) {
if (wnd->friendsList != 0) {
wnd->friendsList->reset();
}
if (wnd->searchResult != 0) {
wnd->searchResult->reset();
}
if (wnd->mapScreen != 0) {
if (wnd->mapScreen->glWidget != 0) {
wnd->mapScreen->glWidget->update();
}
}
}
if (PilotDetails::instance(false) != 0) {
PilotDetails::instance()->refresh();
}
if (ControllerDetails::instance(false) != 0) {
ControllerDetails::instance()->refresh();
}
if (AirportDetails::instance(false) != 0) {
AirportDetails::instance()->refresh();
}
}
bool Settings::resetOnNextStart() {
return instance()->value("main/resetConfiguration", false).toBool();
}
void Settings::setResetOnNextStart(bool value) {
instance()->setValue("main/resetConfiguration", value);
}
// zooming
int Settings::wheelMax() {
return instance()->value("mouseWheel/wheelMax", 120).toInt();
}
void Settings::setWheelMax(int value) {
instance()->setValue("mouseWheel/wheelMax", value);
}
double Settings::zoomFactor() {
return instance()->value("zoom/zoomFactor", 1.0).toDouble();
}
void Settings::setZoomFactor(double value) {
instance()->setValue("zoom/zoomFactor", value);
}
bool Settings::useSelectionRectangle() {
return instance()->value("zoom/selectionRectangle", true).toBool();
}
void Settings::setUseSelctionRectangle(bool value) {
instance()->setValue("zoom/selectionRectangle", value);
}
////////////////////////////////////////
// General
bool Settings::saveWhazzupData() {
return instance()->value("download/saveWhazzupData", true).toBool();
}
void Settings::setSaveWhazzupData(bool value) {
instance()->setValue("download/saveWhazzupData", value);
}
//////////////////////////////////////
// windowmanagment
/////////////////////////////////////
void Settings::setDialogPreferences(const QString &name, const DialogPreferences &dialogPreferences) {
instance()->setValue("windowmanagment/" + name + "Size", dialogPreferences.size);
instance()->setValue("windowmanagment/" + name + "Pos", dialogPreferences.pos);
instance()->setValue("windowmanagment/" + name + "Geo", dialogPreferences.geometry);
}
Settings::DialogPreferences Settings::dialogPreferences(const QString &name) {
return DialogPreferences {
.size = instance()->value("windowmanagment/" + name + "Size").toSize(),
.pos = instance()->value("windowmanagment/" + name + "Pos").toPoint(),
.geometry = instance()->value("windowmanagment/" + name + "Geo").toByteArray()
};
}
void Settings::saveSize(const QSize& size) {
instance()->setValue("mainWindowState/size", size);
}
QSize Settings::savedSize() {
return instance()->value("mainWindowState/size", QSize()).toSize();
}
void Settings::savePosition(const QPoint& pos) {
instance()->setValue("mainWindowState/position", pos);
}
QPoint Settings::savedPosition() {
return instance()->value("mainWindowState/position", QPoint()).toPoint();
}
void Settings::saveState(const QByteArray& state) {
instance()->setValue("mainWindowState/state", state);
}
QByteArray Settings::savedState() {
return instance()->value("mainWindowState/state", QByteArray()).toByteArray();
}
void Settings::saveMaximized(const bool val) {
instance()->setValue("mainWindowState/maximized", val);
}
Qt::SortOrder Settings::airportDialogAtcSortOrder() {
return Qt::SortOrder(instance()->value("airportDialog/atcSortOrder", Qt::AscendingOrder).toInt());
}
void Settings::setAirportDialogAtcSortOrder(Qt::SortOrder v) {
instance()->setValue("airportDialog/atcSortOrder", int(v));
}
QMap<QString, QVariant> Settings::airportDialogAtcExpandedByType() {
return instance()->value("airportDialog/atcExpandedByType", {}).toMap();
}
void Settings::setAirportDialogAtcExpandedByType(const QMap<QString, QVariant>& v) {
instance()->setValue("airportDialog/atcExpandedByType", v);
}
void Settings::saveGeometry(const QByteArray& state) {
instance()->setValue("mainWindowState/geometry", state);
}
QByteArray Settings::savedGeometry() {
return instance()->value("mainWindowState/geometry", QByteArray()).toByteArray();
}
bool Settings::maximized() {
return instance()->value("mainWindowState/maximized", true).toBool();
}
| 54,728
|
C++
|
.cpp
| 1,343
| 36.208488
| 276
| 0.712915
|
qutescoop/qutescoop
| 33
| 15
| 21
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,627
|
Metar.cpp
|
qutescoop_qutescoop/src/Metar.cpp
|
#include "Metar.h"
#include "Airport.h"
#include "NavData.h"
#include "Settings.h"
#include <QRegExp>
Metar::Metar(const QString& encStr, const QString& airportLabel)
: encoded(encStr),
airportLabel(airportLabel),
downloaded(QDateTime::currentDateTime()) {}
bool Metar::isNull() const {
return encoded.isNull();
}
bool Metar::isValid() const {
return encoded.contains(QRegExp("^[A-Z]{4} ")); // Metar must start with 4 capital letters, followed by a blank
}
bool Metar::doesNotExist() const {
return !isNull() && !isValid();
}
bool Metar::needsRefresh() const {
const int ageSec = downloaded.secsTo(QDateTime::currentDateTime());
const bool ret = isNull() || ageSec > Settings::metarDownloadInterval() * 60;
qDebug() << airportLabel << QString("age: %1").arg(ageSec) << "=>" << ret;
return ret;
}
QString Metar::decodeDate(QStringList& tokens) const {
QString date = tokens.first();
tokens.removeFirst();
QString result;
// 012020Z
int day = date.leftRef(2).toInt();
if (day == 1) {
result += "1st";
} else if (day == 2) {
result += "2nd";
} else {
result += QString("%1th").arg(day);
}
date = date.right(5);
result += " on " + date.left(2) + date.right(3).toLower();
return result;
}
QString Metar::decodeWind(QStringList& tokens) const {
QString wind = tokens.first();
QString result = QString();
// 00000KT
if (wind.contains(QRegExp("^00000"))) {
tokens.removeFirst();
return "No wind";
}
//35006KT
if (wind.contains(QRegExp("^[0-9]{5}KT"))) {
tokens.removeFirst();
result = "Wind from " + wind.left(3) + "째@";
wind = wind.right(wind.length() - 3);
result += wind;
}
//13022G25KT
if (wind.contains(QRegExp("^[0-9]{5}G[0-9]{2}KT"))) {
tokens.removeFirst();
result = "Wind from " + wind.left(3) + "째@";
wind.remove(0, 3);
result += wind.left(2) + " ";
wind.remove(0, 3);
result += "Gusts " + wind;
}
// VRB02KT VRB01KT
if (wind.contains(QRegExp("^VRB[0-9]"))) {
tokens.removeFirst();
result = "Wind calm";
}
// 320V040
if (!tokens.isEmpty()) {
QString varying = tokens.first();
if (varying.contains(QRegExp("^[0-9]{3}V[0-9]{3}$"))) {
tokens.removeFirst();
result += "<br>Varying between " + varying.left(3) + "째 and " + varying.right(3) + "째";
}
}
return result;
}
QString Metar::decodeVisibility(QStringList& tokens) const {
if (tokens.isEmpty()) {
return QString();
}
QString vis = tokens.first();
if (vis == "CAVOK") {
tokens.removeFirst();
return "Clouds and visibility OK";
}
// 2 1/2SM
if (vis.length() == 1) {
QString result = "Visibility " + tokens.first();
tokens.removeFirst();
result += " " + tokens.first();
tokens.removeFirst();
return result;
}
// 5SM
if (vis.contains(QRegExp("^[0-9]+SM"))) {
tokens.removeFirst();
return "Visibility " + vis;
}
// xKM
if (vis.contains(QRegExp("^[0-9]+KM"))) {
tokens.removeFirst();
return "Visibility " + vis;
}
bool ok;
int i = vis.toInt(&ok);
if (!ok) {
qWarning() << "unable to parse vis (int):" << vis;
return QString();
}
tokens.removeFirst();
if (i == 9999) {
return "Visibility 10KM or more";
}
if (i < 50) {
return "Visibility less than 50m";
}
if (i % 1000 == 0) {
return QString("Visibility %1KM").arg(i / 1000);
}
return QString("Visibility %1m").arg(i);
}
#define SIG(xy, descr) if (sig.startsWith(xy)) { \
if (!QString(descr).isEmpty()) { result += QString(descr) + " "; } \
sig.remove(0, QString(xy).length()); }
#define SIG2(xy, descr) if (sig.startsWith(xy)) { \
if (!QString(descr).isEmpty()) { result += QString(descr) + " "; } \
sig.remove(0, QString(xy).length()); loop = true; }
QString Metar::decodeSigWX(QStringList& tokens) const {
if (tokens.isEmpty()) {
return QString();
}
QRegExp regex = QRegExp(
QString("^(VC)?") // Proximity
+ "(-|\\+)?" // Intensity
+ "(MI|PR|BC|DR|BL|SH|TS|FZ)?" // Descriptor
+ "(((DZ|RA|SN|SG|IC|PL|GR|GS|UP)+)|" // Precipitation
+ "(BR|FG|FU|VA|DU|SA|HZ|PY))" // Obscuration
+ "(PO|SQ|FC|SS)?"
); // Other
QString sig = tokens.first();
if (!sig.contains(regex)) {
return QString();
}
tokens.removeFirst();
QString result;
SIG("VC", "Vicinity");
if (sig.startsWith("+")) {
result += "heavy "; sig.remove(0, 1);
}
if (sig.startsWith("-")) {
result += "light "; sig.remove(0, 1);
}
SIG("MI", "Shallow");
SIG("PR", "Partial");
SIG("BC", "Patches");
SIG("DR", "Drifting");
SIG("BL", "Blowing");
SIG("SH", "Showers");
SIG("TS", "Thunderstorm");
SIG("FZ", "Freezing");
bool loop;
do {
loop = false;
SIG2("DZ", "Drizzle,");
SIG2("RA", "Rain,");
SIG2("SN", "Snow,");
SIG2("SG", "Snow grains,");
SIG2("IC", "Ice,");
SIG2("PL", "Ice pellets,");
SIG2("GR", "Hail,");
SIG2("GS", "Snow pellets,");
SIG2("UP", "Unknown precipitation,");
} while (loop);
SIG("BR", "Mist,");
SIG("FG", "Fog,");
SIG("FU", "Fume,");
SIG("VA", "Volcanic ash,");
SIG("DU", "Dust,");
SIG("SA", "Sand,");
SIG("HZ", "Haze,");
SIG("PY", "Spray,");
// remove last "," from the string
result = result.trimmed().left(result.length() - 2);
return result;
}
QString Metar::decodeClouds(QStringList& tokens) const {
if (tokens.isEmpty()) {
return QString();
}
QRegExp regex = QRegExp("^(VV|FEW|SCT|BKN|OVC)([0-9]{3}|///)(CB|TCU)?");
QString sig = tokens.first();
if (!sig.contains(regex)) {
return QString();
}
tokens.removeFirst();
QString result;
if (sig.startsWith("VV")) {
return result;
}
SIG("FEW", "Few");
SIG("SCT", "Scattered");
SIG("BKN", "Broken");
SIG("OVC", "Overcast");
if (sig.contains(QRegExp("^[0-9]{3}"))) {
int feet = sig.leftRef(3).toInt();
result += QString("%1").arg(feet) + "00ft";
sig.remove(0, 3);
}
SIG("CB", "Cumulonimbus");
SIG("TCU", "Towering cumulus");
return result;
}
QString Metar::decodeTemp(QStringList& tokens) const {
if (tokens.isEmpty()) {
return QString();
}
QRegExp regex = QRegExp("^(M?[0-9]{2})/(M?[0-9]{2}|//)");
QString sig = tokens.first();
if (!sig.contains(regex)) {
return QString();
}
tokens.removeFirst();
QString result = "Temperature ";
SIG("M", "-");
int i = sig.leftRef(2).toInt();
result += QString("%1").arg(i);
sig.remove(0, 3);
result += ", dew point ";
SIG("M", "-");
i = sig.toInt();
result += QString("%1").arg(i);
return result;
}
QString Metar::decodeQNH(QStringList& tokens) const {
if (tokens.isEmpty()) {
return QString();
}
QString sig = tokens.first();
if (sig.contains(QRegExp("^Q[0-9]{4}"))) {
tokens.removeFirst();
sig.remove(0, 1);
return "QNH " + sig;
}
if (sig.contains(QRegExp("^A[0-9]{4}"))) {
tokens.removeFirst();
sig.remove(0, 1);
QString result = "Altimeter " + sig.left(2);
sig.remove(0, 2);
result += "." + sig;
return result;
}
return QString();
}
QString Metar::decodePrediction(QStringList& tokens) const {
if (tokens.isEmpty()) {
return QString();
}
QString sig = tokens.first();
if (sig.contains(QRegExp("^BECMG"))) {
tokens.removeFirst();
return "Becoming:";
}
if (sig.contains(QRegExp("^NOSIG"))) {
tokens.removeFirst();
return "No significant changes expected.";
}
if (sig.contains(QRegExp("^TEMPO"))) {
tokens.removeFirst();
return "Temporary:";
}
return QString();
}
QString Metar::humanHtml() const {
QString result = "";
QStringList tokens = encoded.split(" ", Qt::SkipEmptyParts);
if (tokens.isEmpty()) {
return "";
}
// LOWW 012020Z 35006KT 320V040 9999 -RA FEW060 SCT070 BKN080 08/05 Q1014 NOSIG
Airport* a = NavData::instance()->airports.value(tokens.first());
if (a == 0) {
result = tokens.first();
} else {
result = a->prettyName();
}
tokens.removeFirst();
result += "<br>";
// ignore recorded time
tokens.removeFirst();
while (!tokens.isEmpty()) {
QString part = decodeWind(tokens);
if (!part.isEmpty()) {
result += part;
}
part = decodeVisibility(tokens);
if (!part.isEmpty()) {
result += "<br>" + part;
}
part = "x";
bool br = false;
while (!part.isEmpty()) {
part = decodeSigWX(tokens);
if (!part.isEmpty()) {
if (!br) {
result += "<br>"; br = true;
} else {
result += ", ";
}
result += part;
}
}
part = "x";
br = false;
while (!part.isEmpty()) {
part = decodeClouds(tokens);
if (!part.isEmpty()) {
if (!br) {
result += "<br>Clouds "; br = true;
} else {
result += ", ";
}
result += part;
}
}
part = decodeTemp(tokens);
if (!part.isEmpty()) {
result += "<br>" + part;
}
part = decodeQNH(tokens);
if (!part.isEmpty()) {
result += "<br>" + part;
}
part = decodePrediction(tokens);
if (part.isEmpty()) {
if (!tokens.isEmpty()) {
if (tokens.first().startsWith("RMK")) {
tokens.clear();
} else {
tokens.removeFirst();
}
}
} else {
result += "<br>" + part + " ";
}
}
return result;
}
| 10,382
|
C++
|
.cpp
| 351
| 22.472934
| 115
| 0.523293
|
qutescoop/qutescoop
| 33
| 15
| 21
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,628
|
GuiMessage.cpp
|
qutescoop_qutescoop/src/GuiMessage.cpp
|
#include "GuiMessage.h"
#include <QApplication>
#include <QMessageBox>
GuiMessages* guiMessagesInstance = 0;
GuiMessages* GuiMessages::instance(bool createIfNoInstance) {
if (guiMessagesInstance == 0) {
if (createIfNoInstance) {
guiMessagesInstance = new GuiMessages();
}
}
return guiMessagesInstance;
}
GuiMessages::GuiMessages()
: _currentStatusMessage(new GuiMessage()),
_currentProgressMessage(new GuiMessage()) {
_timer.setSingleShot(true);
connect(&_timer, &QTimer::timeout, this, &GuiMessages::update);
}
GuiMessages::~GuiMessages() {
delete _currentStatusMessage; delete _currentProgressMessage;
}
///////////////////////////////////////////////////////////////////////////
// STATIC METHODS TO SEND MESSAGES
// text:
void GuiMessages::message(const QString &msg, const QString &id) {
GuiMessages::instance()->updateMessage(new GuiMessage(id, GuiMessage::Temporary, msg));
}
void GuiMessages::warning(const QString &msg, const QString &id) {
GuiMessages::instance()->updateMessage(new GuiMessage(id, GuiMessage::Warning, msg));
}
void GuiMessages::status (const QString &msg, const QString &id) {
GuiMessages::instance()->updateMessage(new GuiMessage(id, GuiMessage::Persistent, msg));
}
void GuiMessages::infoUserAttention(const QString &msg, const QString &id) {
GuiMessages::instance()->updateMessage(
new GuiMessage(id, GuiMessage::InformationUserAttention, msg)
);
}
void GuiMessages::infoUserInteraction(const QString &msg, const QString &titleAndId) {
GuiMessages::instance()->updateMessage(
new GuiMessage(titleAndId, GuiMessage::InformationUserInteraction, msg)
);
}
void GuiMessages::errorUserAttention (const QString &msg, const QString &id) {
GuiMessages::instance()->updateMessage(
new GuiMessage(id, GuiMessage::ErrorUserAttention, msg)
);
}
void GuiMessages::criticalUserInteraction (const QString &msg, const QString &titleAndId) {
GuiMessages::instance()->updateMessage(
new GuiMessage(titleAndId, GuiMessage::CriticalUserInteraction, msg)
);
}
void GuiMessages::fatalUserInteraction (const QString &msg, const QString &titleAndId) {
GuiMessages::instance()->updateMessage(
new GuiMessage(titleAndId, GuiMessage::FatalUserInteraction, msg)
);
}
// progress (including text):
void GuiMessages::progress(const QString &id, int value, int maximum) {
GuiMessages::instance()->updateMessage(
new GuiMessage(id, GuiMessage::ProgressBar, "", value, maximum)
);
}
void GuiMessages::progress(const QString &id, const QString &msg) {
GuiMessages::instance()->updateMessage(
new GuiMessage(id, GuiMessage::ProgressBar, msg)
);
}
void GuiMessages::remove(const QString &id) {
if (!id.isEmpty()) {
GuiMessages::instance()->removeMessageById(id);
}
}
///////////////////////////////////////////////////////////////////////////
// METHODS TO SET ACTIVE OUTPUT WIDGETS
void GuiMessages::addStatusLabel(QLabel* label, bool hideIfNothingToDisplay) {
// we want to be notified before this QLabel is getting invalid
connect(label, &QObject::destroyed, this, &GuiMessages::labelDestroyed);
_labels.insert(label, hideIfNothingToDisplay);
update();
}
void GuiMessages::removeStatusLabel(QLabel* label) {
if (_labels[label]) {
label->hide();
}
_labels.remove(label);
}
void GuiMessages::labelDestroyed(QObject* obj) {
if (static_cast<QLabel*>(obj) != 0) {
if (_labels.remove(static_cast<QLabel*>(obj)) == 0) {
qWarning() << "object not found";
}
} else {
qWarning() << "invalid object cast";
}
}
void GuiMessages::addProgressBar(QProgressBar* progressBar, bool hideIfNothingToDisplay) {
// we want to be notified before this QProgressBar is getting invalid
connect(progressBar, &QObject::destroyed, this, &GuiMessages::progressBarDestroyed);
_bars.insert(progressBar, hideIfNothingToDisplay);
update();
}
void GuiMessages::removeProgressBar(QProgressBar* progressBar) {
if (_bars[progressBar]) {
progressBar->hide();
}
_bars.remove(progressBar);
}
void GuiMessages::progressBarDestroyed(QObject* obj) {
if (static_cast<QProgressBar*>(obj) != 0) {
if (_bars.remove(static_cast<QProgressBar*>(obj)) == 0) {
qWarning() << "GuiMessages::progressBarDestroyed() object not found";
}
} else {
qWarning() << "GuiMessages::progressBarDestroyed() invalid object cast";
}
}
///////////////////////////////////////////////////////////////////////////
// INTERNALLY USED CLASS AND METHODS (called by static methods)
void GuiMessages::updateMessage(GuiMessage* gm) {
GuiMessage* existing = messageById(gm->id, gm->type);
if (existing != 0) {
if (!gm->msg.isEmpty()) {
existing->msg = gm->msg;
}
if (gm->progressValue != -1) {
existing->progressValue = gm->progressValue;
}
if (gm->progressMaximum != -1) {
existing->progressMaximum = gm->progressMaximum;
}
if (gm->showMs != -1) {
existing->showMs = gm->showMs;
}
if (gm->shownSince.isValid()) {
existing->shownSince = gm->shownSince;
}
} else {
_messages.insert(gm->type, gm);
}
update();
}
void GuiMessages::removeMessageById(const QString &id) {
foreach (int key, _messages.keys()) {
foreach (GuiMessage* gm, _messages.values(key)) {
if (gm->id == id) {
if (_currentStatusMessage == gm) {
setStatusMessage(new GuiMessage());
}
if (_currentProgressMessage == gm) {
setProgress(new GuiMessage());
}
_messages.remove(key, gm);
}
}
}
update();
}
///////////////////////////////////////////////////////////////////////////
// PRIVATE METHODS
void GuiMessages::setStatusMessage(GuiMessage* gm, bool, bool, bool instantRepaint) {
foreach (QLabel* l, _labels.keys()) {
l->setText(gm->msg);
if (_labels[l]) { // bool indicating hideIfNothingToDisplay
const bool visible = !gm->msg.isEmpty()
&& (gm->type != GuiMessage::Uninitialized);
l->setVisible(visible);
}
if (instantRepaint) {
l->repaint();
}
}
_currentStatusMessage = (gm->msg.isEmpty()? 0: gm);
if (!gm->shownSince.isValid()) {
gm->shownSince = QDateTime::currentDateTimeUtc();
}
}
void GuiMessages::setProgress(GuiMessage* gm, bool instantRepaint) {
foreach (QProgressBar* pb, _bars.keys()) {
if (gm->progressMaximum != -1) {
pb->setMaximum(gm->progressMaximum);
}
pb->setValue(gm->progressValue);
if (_bars[pb]) { // boolean inicating hideIfNohingToDisplay
const bool visible =
(gm->progressValue != gm->progressMaximum)
|| (gm->progressMaximum == -1 && gm->progressValue != -1);
pb->setVisible(visible);
}
if (instantRepaint) {
pb->repaint();
}
}
_currentProgressMessage = gm;
}
void GuiMessages::update() {
foreach (int key, _messages.keys()) {
foreach (GuiMessage* gm, _messages.values(key)) {
if (
gm->showMs != -1 && gm->shownSince.isValid() // shown long enough
&& gm->shownSince.addMSecs(gm->showMs)
< QDateTime::currentDateTimeUtc()
) {
removeMessageById(gm->id);
} else {
switch (gm->type) {
case GuiMessage::FatalUserInteraction:
QMessageBox::critical(nullptr, gm->id, gm->msg);
qFatal("%s %s", (const char*) gm->id.constData(), (const char*) gm->msg.constData());
_messages.remove(key, gm);
return;
case GuiMessage::CriticalUserInteraction:
QMessageBox::critical(nullptr, gm->id, gm->msg);
qCritical("%s %s", (const char*) gm->id.constData(), (const char*) gm->msg.constData());
_messages.remove(key, gm);
return;
case GuiMessage::ErrorUserAttention:
gm->showMs = 5000;
setStatusMessage(gm, true);
_timer.start(gm->showMs);
return;
case GuiMessage::Warning:
gm->showMs = 3000;
setStatusMessage(gm, false, true);
_timer.start(gm->showMs);
return;
case GuiMessage::InformationUserAttention:
gm->showMs = 3000;
setStatusMessage(gm, true);
_timer.start(gm->showMs);
return;
case GuiMessage::InformationUserInteraction:
QMessageBox::information(nullptr, gm->id, gm->msg);
_messages.remove(key, gm);
return;
case GuiMessage::ProgressBar:
gm->showMs = 10000; // timeout value
setStatusMessage(gm);
_timer.start(gm->showMs);
if (gm->progressValue != -1) {
setProgress(gm);
}
break; // looking further for messages
case GuiMessage::Temporary:
gm->showMs = 3000;
setStatusMessage(gm);
_timer.start(gm->showMs);
return;
case GuiMessage::Persistent:
setStatusMessage(gm);
setProgress(new GuiMessage());
return;
default: {}
}
}
}
}
}
GuiMessages::GuiMessage* GuiMessages::messageById(const QString &id, const GuiMessage::Type &type) {
foreach (GuiMessage* gm, _messages) {
if (gm->id == id && (type == GuiMessage::All || gm->type == type)) {
return gm;
}
}
return 0;
}
///////////////////////////////////////////////////////////////////////////////
// GuiMessages::GuiMessage qDebug() compatibility
QDebug operator<<(QDebug dbg, const GuiMessages::GuiMessage* gm) {
dbg.nospace() << "id: " << gm->id << ", msg: " << gm->msg
<< ", type " << gm->type << ", val: " << gm->progressValue
<< ", max: " << gm->progressMaximum
<< ", since: " << gm->shownSince.toString(Qt::ISODate)
<< ", ms: " << gm->showMs;
return dbg.maybeSpace();
}
GuiMessages::GuiMessage::~GuiMessage() {}
| 11,038
|
C++
|
.cpp
| 278
| 30.176259
| 112
| 0.560715
|
qutescoop/qutescoop
| 33
| 15
| 21
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,629
|
BookedController.cpp
|
qutescoop_qutescoop/src/BookedController.cpp
|
#include "BookedController.h"
#include "Settings.h"
#include <QJsonObject>
BookedController::BookedController(const QJsonObject& json) {
callsign = json["callsign"].toString();
Q_ASSERT(!callsign.isNull());
userId = QString::number(json["cid"].toInt());
bookingType = json["type"].toString();
timeConnected = m_starts = QDateTime::fromString(json["start"].toString() + "Z", "yyyy-MM-dd HH:mm:sst");
m_ends = QDateTime::fromString(json["end"].toString() + "Z", "yyyy-MM-dd HH:mm:sst");
if (bookingType == "booking") {
bookingInfoStr = "";
} else if (bookingType == "event") {
bookingInfoStr = "Event";
} else if (bookingType == "training") {
bookingInfoStr = "Training";
} else {
bookingInfoStr = bookingType;
}
if (callsign.right(5) == "_ATIS") {
facilityType = 2;
} else if (callsign.right(4) == "_DEL") {
facilityType = 2;
} else if (callsign.right(4) == "_GND") {
facilityType = 3;
} else if (callsign.right(4) == "_TWR") {
facilityType = 4;
} else if (callsign.right(4) == "_APP" || callsign.right(4) == "_DEP") {
facilityType = 5;
} else if (callsign.right(4) == "_CTR") {
facilityType = 6;
} else if (callsign.right(4) == "_FSS") {
facilityType = 7;
}
}
QString BookedController::facilityString() const {
switch (facilityType) {
case 0: return "OBS";
case 1: return "Staff";
case 2: return "DEL";
case 3: return "GND";
case 4: return "TWR";
case 5: return "APP";
case 6: return "CTR";
case 7: return "FSS";
}
return QString();
}
const QString BookedController::realName() const {
auto& _alias = Settings::clientAlias(userId);
if (!_alias.isEmpty()) {
return _alias;
}
return userId;
}
bool BookedController::isFriend() const {
return Settings::friends().contains(userId);
}
QDateTime BookedController::starts() const {
return m_starts;
}
QDateTime BookedController::ends() const {
return m_ends;
}
| 2,091
|
C++
|
.cpp
| 64
| 27.1875
| 109
| 0.606151
|
qutescoop/qutescoop
| 33
| 15
| 21
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,630
|
MetarSearchVisitor.cpp
|
qutescoop_qutescoop/src/MetarSearchVisitor.cpp
|
#include "Airport.h"
#include "MetarSearchVisitor.h"
void MetarSearchVisitor::visit(MapObject* object) {
Airport* a = dynamic_cast<Airport*>(object);
if (a == 0) {
return;
}
if (a->id.contains(_regex)) {
_airportMap[a->id] = a;
}
}
QList<Airport*> MetarSearchVisitor::airports() const {
QList<Airport*> res;
QList<QString> labels = _airportMap.keys();
labels.sort();
for (int i = 0; i < labels.size(); i++) {
res.append(_airportMap[labels[i]]);
}
return res;
}
QList<MapObject*> MetarSearchVisitor::result() const {
QList<MapObject*> res;
QList<Airport*> airpts = airports();
for (int i = 0; i < airpts.size(); i++) {
res.append(airpts[i]);
}
return res;
}
| 759
|
C++
|
.cpp
| 28
| 22.464286
| 54
| 0.611034
|
qutescoop/qutescoop
| 33
| 15
| 21
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,631
|
Pilot.cpp
|
qutescoop_qutescoop/src/Pilot.cpp
|
#include "Pilot.h"
#include "Airac.h"
#include "Airport.h"
#include "Client.h"
#include "helpers.h"
#include "NavData.h"
#include "Settings.h"
#include "Whazzup.h"
#include "dialogs/PilotDetails.h"
#include "src/mustache/Renderer.h"
#include <QJsonObject>
int Pilot::altToFl(int alt_ft, int qnh_mb) {
float diff = qnh_mb - 1013.25;
// https://edwilliams.org/avform147.htm
// https://www.pprune.org/tech-log/123900-temp-height-change-per-millibar.html
// 30ft per mb - this is what xPilot uses for XP11
float fl_ft = alt_ft - diff * 30;
return qRound(fl_ft / 100.);
}
Pilot::Pilot(const QJsonObject& json, const WhazzupData* whazzup)
: MapObject(), Client(json, whazzup),
airline(0) {
whazzupTime = QDateTime(whazzup->whazzupTime); // need some local reference to that
lat = json["latitude"].toDouble();
lon = json["longitude"].toDouble();
pilotRating = json["pilot_rating"].toInt();
militaryRating = json["military_rating"].toInt();
altitude = json["altitude"].toInt();
groundspeed = json["groundspeed"].toInt();
QJsonObject flightPlan = json["flight_plan"].toObject();
// The JSON data provides 3 different aircraft data
// 1: The full ICAO Data, this is too long to display
// 2: The FAA Data, this is what was displayed previously
// 3: The short Data, consisting only of the aircraft code
planAircraftFull = flightPlan["aircraft"].toString();
planAircraftShort = flightPlan["aircraft_short"].toString();
planAircraftFaa = flightPlan["aircraft_faa"].toString();
planTAS = flightPlan["cruise_tas"].toString();
planDep = flightPlan["departure"].toString();
planAlt = flightPlan["altitude"].toString();
planDest = flightPlan["arrival"].toString();
QRegExp _airlineRegEx("([A-Z]{3})[0-9].*");
if (_airlineRegEx.exactMatch(callsign)) {
auto _capturedTexts = _airlineRegEx.capturedTexts();
airline = NavData::instance()->airlines.value(_capturedTexts[1], 0);
}
transponder = json["transponder"].toString();
transponderAssigned = flightPlan["assigned_transponder"].toString();
planRevision = QString::number(flightPlan["revision_id"].toInt());
planFlighttype = flightPlan["flight_rules"].toString();
planDeptime = flightPlan["deptime"].toString();
planActtime = flightPlan["deptime"].toString(); // The new data doesn't provide the actual departure
QString timeEnroute = flightPlan["enroute_time"].toString();
QString timeFuel = flightPlan["fuel_time"].toString();
QString tmpStr = timeEnroute.left(2);
if (tmpStr.isNull()) {
planEnroute_hrs = -1;
} else {
planEnroute_hrs = tmpStr.toInt();
}
planEnroute_mins = timeEnroute.rightRef(2).toInt();
planFuel_hrs = timeFuel.leftRef(2).toInt();
planFuel_mins = timeFuel.rightRef(2).toInt();
planAltAirport = flightPlan["alternate"].toString();
planRemarks = flightPlan["remarks"].toString();
planRoute = flightPlan["route"].toString();
trueHeading = json["heading"].toInt();
qnh_inHg = json["qnh_i_hg"].toDouble();
qnh_mb = json["qnh_mb"].toInt();
// day of flight
if (!QTime::fromString(planDeptime, "HHmm").isValid()) { // no Plan ETA given: maybe some more magic needed here
dayOfFlight = whazzupTime.date();
} else if ((QTime::fromString(planDeptime, "HHmm").hour() - whazzupTime.time().hour()) % 24 <= 2) {
// allow for early birds (up to 2 hours before planned departure)
dayOfFlight = whazzupTime.date();
} else {
dayOfFlight = whazzupTime.date().addDays(-1); // started the day before
}
checkStatus();
}
Pilot::~Pilot() {
MustacheQs::Renderer::teardownContext(this);
}
void Pilot::showDetailsDialog() {
PilotDetails* infoDialog = PilotDetails::instance();
infoDialog->refresh(this);
infoDialog->show();
infoDialog->raise();
infoDialog->setFocus();
infoDialog->activateWindow();
}
QString Pilot::mapLabel() const {
auto tmpl = Settings::pilotPrimaryContent();
return MustacheQs::Renderer::render(tmpl, (QObject*) this);
}
QString Pilot::mapLabelHovered() const {
auto tmpl = Settings::pilotPrimaryContentHovered();
return MustacheQs::Renderer::render(tmpl, (QObject*) this);
}
QStringList Pilot::mapLabelSecondaryLines() const {
auto tmpl = Settings::pilotSecondaryContent();
return Helpers::linesFilteredTrimmed(
MustacheQs::Renderer::render(tmpl, (QObject*) this)
);
}
QStringList Pilot::mapLabelSecondaryLinesHovered() const {
auto tmpl = Settings::pilotSecondaryContentHovered();
return Helpers::linesFilteredTrimmed(
MustacheQs::Renderer::render(tmpl, (QObject*) this)
);
}
Pilot::FlightStatus Pilot::flightStatus() const {
Airport* dep = depAirport();
Airport* dst = destAirport();
if (qFuzzyIsNull(lat) && qFuzzyIsNull(lon)) {
return PREFILED;
}
// flying?
const bool flying = groundspeed > 50 || altitude > 9000;
if (dep == 0 || dst == 0) {
if (flying) {
return EN_ROUTE;
}
return BUSH;
}
const double totalDist = NavData::distance(dep->lat, dep->lon, dst->lat, dst->lon);
const double distDone = NavData::distance(lat, lon, dep->lat, dep->lon);
const double distRemaining = totalDist - distDone;
// arriving?
const bool arriving = distRemaining < 50 && distRemaining < distDone;
// departing?
const bool departing = distDone < 50 && distRemaining > distDone;
// BOARDING: !flying, speed = 0, departing
// GROUND_DEP: !flying, speed > 0, departing
// DEPARTING: flying, departing
// EN_ROUTE: flying, !departing, !arriving
// ARRIVING: flying, arriving
// GROUND_ARR: !flying, speed > 0, arriving
// BLOCKED: !flying, speed = 0, arriving
// PREFILED: !flying, lat=0, lon=0
if (!flying && groundspeed == 0 && departing) {
return BOARDING;
}
if (!flying && groundspeed > 0 && departing) {
return GROUND_DEP;
}
if (flying && arriving) {
return ARRIVING; // put before departing; on small hops tend to show "arriving", not departing
}
if (flying && departing) {
return DEPARTING;
}
if (flying && !departing && !arriving) {
return EN_ROUTE;
}
if (!flying && groundspeed > 0 && arriving) {
return GROUND_ARR;
}
if (!flying && groundspeed == 0 && arriving) {
return BLOCKED;
}
return CRASHED; // should never happen
}
QString Pilot::flightStatusString() const {
QString result;
switch (flightStatus()) {
case BOARDING:
return "TTG " + eet().toString("H:mm") + " hrs"
+ ", ETA " + eta().toString("HHmm") + "z"
+ (delayString().isEmpty()? "": ", Delay " + delayString());
case GROUND_DEP:
return "TTG " + eet().toString("H:mm") + " hrs"
+ ", ETA " + eta().toString("HHmm") + "z"
+ (delayString().isEmpty()? "": ", Delay " + delayString());
case DEPARTING:
return "TTG " + eet().toString("H:mm") + " hrs"
+ ", ETA " + eta().toString("HHmm") + "z"
+ (delayString().isEmpty()? "": ", Delay " + delayString());
case ARRIVING:
return "TTG " + eet().toString("H:mm") + " hrs"
+ ", ETA " + eta().toString("HHmm") + "z"
+ (delayString().isEmpty()? "": ", Delay " + delayString());
case GROUND_ARR:
return "ATA " + eta().toString("HHmm") + "z" // Actual Time of Arrival :)
+ (delayString().isEmpty()? "": ", Delay " + delayString());
case BLOCKED:
return "ATA " + eta().toString("HHmm") + "z" // Actual Time of Arrival :)
+ (delayString().isEmpty()? "": ", Delay " + delayString());
case CRASHED: return "";
case BUSH: return "";
case EN_ROUTE: {
result = "";
Airport* dep = depAirport();
Airport* dst = destAirport();
if (dst == 0) {
return result;
}
if (dep != 0) {
// calculate %done
int total_dist = (int) NavData::distance(dep->lat, dep->lon, dst->lat, dst->lon);
if (total_dist > 0) {
int dist_done = (int) NavData::distance(lat, lon, dep->lat, dep->lon);
result += QString("%1%").arg(dist_done * 100 / total_dist);
}
}
result += ", TTG " + eet().toString("H:mm") + " hrs";
result += ", ETA " + eta().toString("HHmm") + "z";
result += (delayString().isEmpty()? "": ", Delay " + delayString());
return result;
}
case PREFILED:
return "";
}
return "Unknown";
}
QString Pilot::flightStatusShortString() const {
switch (flightStatus()) {
case BOARDING: return "boarding";
case GROUND_DEP: return QString("taxiing out");
case DEPARTING: return QString("departing");
case ARRIVING: return QString("arriving");
case GROUND_ARR: return QString("taxiing in");
case BLOCKED: return QString("blocked");
case CRASHED: return QString("crashed");
case BUSH: return QString("bush pilot");
case EN_ROUTE: return QString("en route");
case PREFILED: return QString("prefiled");
default: return QString("unknown");
}
}
QString Pilot::planFlighttypeString() const {
if (planFlighttype == "I") {
return QString("IFR");
} else if (planFlighttype == "V") {
return QString("VFR");
} else if (planFlighttype == "Y") {
return QString("Y: IFR to VFR");
} else if (planFlighttype == "Z") {
return QString("Z: VFR to IFR");
} else if (planFlighttype == "S") {
return QString("SVFR");
} else {
return QString(planFlighttype);
}
}
QString Pilot::toolTip() const {
QString result = callsign + " (" + realName();
if (!rank().isEmpty()) {
result += ", " + rank();
}
return result += ")"
+ (!planDep.isEmpty() || !planDest.isEmpty()? " " + planDep + "-" + planDest: "")
+ (!planAircraftShort.isEmpty()? ", " + planAircraftShort: "")
;
}
QString Pilot::rank() const {
QStringList ret;
if (pilotRating > 0) { // we hide "NEW"
auto pilotRatingString = Whazzup::instance()->realWhazzupData().pilotRatings.value(pilotRating, QString("#%1").arg(pilotRating));
ret << pilotRatingString;
}
if (militaryRating > 0) { // we hide "M0"
auto militaryRatingString = Whazzup::instance()->realWhazzupData().militaryRatings.value(militaryRating, QString("#%1").arg(militaryRating));
ret << militaryRatingString;
}
return ret.join(" ");
}
Airport* Pilot::depAirport() const {
return NavData::instance()->airports.value(planDep, 0);
}
Airport* Pilot::destAirport() const {
return NavData::instance()->airports.value(planDest, 0);
}
Airport* Pilot::altAirport() const {
return NavData::instance()->airports.value(planAltAirport, 0);
}
double Pilot::distanceFromDeparture() const {
Airport* dep = depAirport();
if (dep == 0) {
return 0;
}
return NavData::distance(lat, lon, dep->lat, dep->lon);
}
double Pilot::distanceToDestination() const {
Airport* dest = destAirport();
if (dest == 0) {
return 0;
}
if (flightStatus() == Pilot::PREFILED) {
Airport* dep = depAirport();
if (dep == 0) {
return 0;
}
return NavData::distance(dep->lat, dep->lon, dest->lat, dest->lon);
}
return NavData::distance(lat, lon, dest->lat, dest->lon);
}
int Pilot::planTasInt() const { // defuck flightplanned TAS
if (planTAS.startsWith("M")) { // approximate Mach -> TAS conversion
if (planTAS.contains(".")) {
return (int) planTAS.mid(1).toDouble() * 550;
} else {
return static_cast<int>(planTAS.mid(1).toInt() * 5.5);
}
}
return planTAS.toInt();
}
QDateTime Pilot::etd() const { // Estimated Time of Departure - but according to the web form SOBT
QString planDeptimeFixed = planDeptime;
if (planDeptime.length() == 3) {
planDeptimeFixed.prepend("0"); // fromString("Hmm") does not handle "145" correctly -> "14:05"
}
QTime time = QTime::fromString(planDeptimeFixed, "HHmm");
return QDateTime(dayOfFlight, time, Qt::UTC);
}
QDateTime Pilot::eta() const { // Estimated Time of Arrival
FlightStatus status = flightStatus();
if (status == PREFILED || status == BOARDING) {
if (whazzupTime < etaPlan()) {
return etaPlan();
}
return whazzupTime.addSecs(etd().secsTo(etaPlan()));
} else if (status == DEPARTING || status == GROUND_DEP) { // try to calculate with flightplanned speed
int enrouteSecs;
if (planTasInt() == 0) {
if (groundspeed == 0) {
return QDateTime(); // abort
}
enrouteSecs = (int) (distanceToDestination() * 3600) / groundspeed;
} else {
enrouteSecs = (int) (distanceToDestination() * 3600) / planTasInt();
}
if (status == GROUND_DEP) {
enrouteSecs += taxiTimeOutbound; // taxi time outbound
}
return whazzupTime.addSecs(enrouteSecs);
} else if (status == EN_ROUTE || status == ARRIVING) { // try groundspeed
int enrouteSecs;
if (groundspeed == 0) {
if (planTasInt() == 0) {
return QDateTime(); // abort
}
enrouteSecs = (int) (distanceToDestination() * 3600) / planTasInt();
} else {
enrouteSecs = (int) (distanceToDestination() * 3600) / groundspeed;
}
return whazzupTime.addSecs(enrouteSecs);
} else if (status == GROUND_ARR || status == BLOCKED) {
return whazzupTime;
}
return QDateTime();
}
QTime Pilot::eet() const { // Estimated Enroute Time remaining
int secs = whazzupTime.secsTo(eta());
return QTime((secs / 3600) % 24, (secs / 60) % 60);
}
QDateTime Pilot::etaPlan() const { // Estimated Time of Arrival as flightplanned
if (planEnroute_hrs < 0) {
return QDateTime();
}
return etd().addSecs(planEnroute_hrs * 3600 + planEnroute_mins * 60);
}
QString Pilot::delayString() const { // delay
auto status = flightStatus();
if (status == BOARDING || status == GROUND_DEP || status == PREFILED) {
// output delta to planned off-block
auto secs = etd().secsTo(whazzupTime);
auto calcSecs = (secs < 0? -secs: secs);
return QString("%1%2 hrs")
.arg(secs < 0? "-": "", QTime((calcSecs / 3600) % 24, (calcSecs / 60) % 60).toString("H:mm"));
}
if (!etaPlan().isValid()) {
return "";
}
auto secs = etaPlan().secsTo(eta());
if (secs == 0) {
return QString("n/a");
}
auto calcSecs = (secs < 0? -secs: secs);
return QString("%1%2 hrs")
.arg(secs < 0? "-": "", QTime((calcSecs / 3600) % 24, (calcSecs / 60) % 60).toString("H:mm"));
}
int Pilot::defuckPlanAlt(QString altStr) const { // returns an altitude from various flightplan strings
altStr = altStr.trimmed();
if (altStr.length() < 4 && altStr.toInt() != 0) { // 280: naive mode
return altStr.toInt() * 100;
}
if (altStr.leftRef(2) == "FL") { // FL280: bastard mode
return altStr.midRef(2).toInt() * 100;
}
if (altStr.leftRef(1) == "F") { // F280
return altStr.midRef(1).toInt() * 100;
}
if (altStr.leftRef(1) == "A" && altStr.length() <= 4) { // A45
return altStr.midRef(1).toInt() * 100;
}
if (altStr.leftRef(1) == "A" && altStr.length() > 4) { // A4500: idiot mode...
return altStr.midRef(1).toInt();
}
if (altStr.leftRef(1) == "S") { // S1130 (FL 1130m)
return mToFt(altStr.midRef(1).toInt());
}
if (altStr.leftRef(1) == "M" && altStr.length() <= 4) { // M0840 (840m)
return mToFt(altStr.midRef(1).toInt());
}
return altStr.toInt();
}
QString Pilot::humanAlt() const {
if (altitude < 10000) {
return QString("%1 ft").arg(round(altitude / 100.) * 100);
}
return QString("FL %1").arg(Pilot::altToFl(altitude, qnh_mb));
}
QString Pilot::flOrEmpty() const {
if (groundspeed == 0) {
return "";
}
return QString("F%1").arg(Pilot::altToFl(altitude, qnh_mb));
}
QStringList Pilot::waypoints() const {
// @todo put this into a RouteResolver
auto parts = planRoute.toUpper().split(
QRegExp(
"[\\s\\-+.,/]|"
"\\b(?:[MNAFSMK]\\d{3,4}){2,}\\b|"
"\\b\\d{2}\\D?\\b|"
"DCT"
),
Qt::SkipEmptyParts
); // split and throw away DCT + /N450F230 etc.
if (!parts.isEmpty()) {
if (parts.constFirst() == planDep) {
parts.removeFirst();
}
}
if (!parts.isEmpty()) {
if (parts.constLast() == planDest) {
parts.removeLast();
}
}
return parts;
}
QPair<double, double> Pilot::positionInFuture(int seconds) const {
double dist = (double) groundspeed * ((double) seconds / 3600.0);
return NavData::pointDistanceBearing(lat, lon, dist, trueHeading);
}
int Pilot::nextPointOnRoute(const QList<Waypoint*> &waypoints) const { // next point after present position
if ((qFuzzyIsNull(lat) && qFuzzyIsNull(lon)) || waypoints.isEmpty()) {
return 0; // prefiled flight or no known position
}
int nextPoint;
// find the point that is nearest to the plane
double minDist = NavData::distance(
lat, lon, waypoints[0]->lat,
waypoints[0]->lon
);
int minPoint = 0; // next to departure as default
for (int i = 1; i < waypoints.size(); i++) {
if (NavData::distance(lat, lon, waypoints[i]->lat, waypoints[i]->lon) < minDist) {
minDist = NavData::distance(lat, lon, waypoints[i]->lat, waypoints[i]->lon);
minPoint = i;
}
}
// with the nearest point, look which one is the next point ahead - saves from trouble with zig-zag routes
if (minPoint == 0) {
nextPoint = 1;
} else if (minPoint == waypoints.size() - 1) {
nextPoint = waypoints.size() - 1;
} else {
nextPoint = minPoint + 1; // default
// look for the first route segment where the planned course deviates > 90° from the bearing to the
// plane
int courseRoute, courseToPlane, courseDeviation;
for (int i = minPoint - 1; i <= minPoint; i++) {
courseRoute = (int) NavData::courseTo(
waypoints[i]->lat, waypoints[i]->lon,
waypoints[i + 1]->lat, waypoints[i + 1]->lon
);
courseToPlane = (int) NavData::courseTo(
waypoints[i]->lat, waypoints[i]->lon,
lat, lon
);
courseDeviation = (qAbs(courseRoute - courseToPlane)) % 360;
if (courseDeviation > 90) {
nextPoint = i;
break;
}
}
}
return qMin(nextPoint, waypoints.size());
}
QString Pilot::livestreamString() const {
return Client::livestreamString(planRemarks);
}
bool Pilot::hasPrimaryAction() const {
return true;
}
void Pilot::primaryAction() {
showDetailsDialog();
}
QList<Waypoint*> Pilot::routeWaypoints() {
if (
(planDep == routeWaypointsPlanDepCache) // we might have cached the route already
&& (planDest == routeWaypointsPlanDestCache)
&& (planRoute == routeWaypointsPlanRouteCache)
) {
return routeWaypointsCache; // no changes
}
routeWaypointsPlanDepCache = planDep;
routeWaypointsPlanDestCache = planDest;
routeWaypointsPlanRouteCache = planRoute;
const double maxDist = planFlighttype == "I"
? Airac::ifrMaxWaypointInterval
: Airac::nonIfrMaxWaypointInterval;
if (depAirport() != 0) {
routeWaypointsCache = Airac::instance()->resolveFlightplan(
waypoints(), depAirport()->lat, depAirport()->lon, maxDist
);
} else if (!qFuzzyIsNull(lat) || !qFuzzyIsNull(lon)) {
routeWaypointsCache = Airac::instance()->resolveFlightplan(
waypoints(), lat, lon, maxDist
);
} else {
routeWaypointsCache = QList<Waypoint*>();
}
return routeWaypointsCache;
}
QString Pilot::routeWaypointsString() {
QStringList ret;
foreach (const Waypoint* w, routeWaypoints()) {
ret.append(w->id);
}
return ret.join(" ");
}
QList<Waypoint*> Pilot::routeWaypointsWithDepDest() {
QList<Waypoint*> waypoints = routeWaypoints();
if (depAirport() != 0) {
waypoints.prepend(new Waypoint(depAirport()->id, depAirport()->lat, depAirport()->lon));
}
if (destAirport() != 0) {
waypoints.append(new Waypoint(destAirport()->id, destAirport()->lat, destAirport()->lon));
}
return waypoints;
}
void Pilot::checkStatus() {
drawLabel = flightStatus() == Pilot::DEPARTING
|| flightStatus() == Pilot::EN_ROUTE
|| flightStatus() == Pilot::ARRIVING
|| flightStatus() == Pilot::CRASHED
|| flightStatus() == Pilot::BUSH
|| flightStatus() == Pilot::PREFILED;
}
| 21,456
|
C++
|
.cpp
| 552
| 31.967391
| 149
| 0.602584
|
qutescoop/qutescoop
| 33
| 15
| 21
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,632
|
SectorReader.cpp
|
qutescoop_qutescoop/src/SectorReader.cpp
|
#include "SectorReader.h"
#include "FileReader.h"
#include "helpers.h"
#include "Settings.h"
SectorReader::SectorReader() {}
SectorReader::~SectorReader() {}
void SectorReader::loadSectors(QMultiMap<QString, Sector*> §ors) {
sectors.clear();
loadSectorlist(sectors);
loadSectordisplay(sectors);
}
void SectorReader::loadSectorlist(QMultiMap<QString, Sector*>& sectors) {
auto filePath = "data/firlist.dat";
FileReader* fileReader = new FileReader(Settings::dataDirectory(filePath));
auto count = 0;
while (!fileReader->atEnd()) {
++count;
QString line = fileReader->nextLine();
if (line.isEmpty() || line.startsWith(";")) {
continue;
}
Sector* sector = new Sector(line.split(':'), count);
if (sector->isNull()) {
delete sector;
continue;
}
sectors.insert(sector->icao, sector);
}
delete fileReader;
}
void SectorReader::loadSectordisplay(QMultiMap<QString, Sector*>& sectors) {
auto filePath = "data/firdisplay.dat";
FileReader* fileReader = new FileReader(Settings::dataDirectory(filePath));
QString workingSectorId;
QList<QPair<double, double> > pointList;
unsigned int count = 0;
unsigned int debugLineWorkingSectorStart = 0;
while (!fileReader->atEnd()) {
++count;
QString line = fileReader->nextLine();
if (line.isEmpty() || line.startsWith(";")) {
continue;
}
// DISPLAY_LIST_100 or DISPLAY_LIST_EDFM-APP
// 51.08:2.55
// ...
// DISPLAY_LIST_ // last line is always DISPLAY_LIST_
if (line.startsWith("DISPLAY_LIST_")) {
if (!workingSectorId.isEmpty()) { // we are at the end of a section
if (pointList.size() < 3) {
QMessageLogger(filePath, debugLineWorkingSectorStart, QT_MESSAGELOG_FUNC).critical()
<< "Sector" << workingSectorId << "doesn't contain enough points (" << pointList.size() << ", expected 3+)";
exit(EXIT_FAILURE);
}
QList<Sector*> sectorsWithMatchingId;
foreach (const auto sector, sectors) {
if (sector->id == workingSectorId) {
sectorsWithMatchingId.append(sector);
}
}
if (sectorsWithMatchingId.size() == 0) {
QMessageLogger(filePath, count, QT_MESSAGELOG_FUNC).info()
<< line << "Sector ID" << workingSectorId << "is not used in firlist.dat.";
// add this pseudo sector to be able to show it in StaticSectorsDialog
auto* s = new Sector(
{
"ZZZZ " + workingSectorId,
"not used by any controller",
NULL,
NULL,
NULL,
workingSectorId,
},
-1,
debugLineWorkingSectorStart
);
s->setPoints(pointList);
sectors.insert(NULL, s);
}
foreach (const auto sector, sectorsWithMatchingId) {
if (sector != 0) {
sector->setDebugSectorLineNumber(debugLineWorkingSectorStart);
sector->setPoints(pointList);
}
}
}
// new section starts here
workingSectorId = line.split('_').last();
debugLineWorkingSectorStart = count;
pointList.clear();
} else if (!workingSectorId.isEmpty()) {
QStringList latLng = line.split(':');
if (latLng.size() < 2) {
continue;
}
double lat = latLng[0].toDouble();
double lon = Helpers::modPositive(latLng[1].toDouble() + 180., 360.) - 180.;
if (lat > 90. || lat < -90. || lon > 180. || lon < -180. || (qFuzzyIsNull(lat) && qFuzzyIsNull(lon))) {
QMessageLogger(filePath, count, QT_MESSAGELOG_FUNC).critical()
<< line << ": Sector id" << workingSectorId << "has invalid point" << lat << lon;
exit(EXIT_FAILURE);
}
pointList.append(QPair<double, double>(lat, lon));
}
}
delete fileReader;
}
| 4,523
|
C++
|
.cpp
| 107
| 29.140187
| 132
| 0.525717
|
qutescoop/qutescoop
| 33
| 15
| 21
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,633
|
Platform.cpp
|
qutescoop_qutescoop/src/Platform.cpp
|
#include "Platform.h"
QString Platform::platformOS() {
return QString("%1:%2:%3").arg(QSysInfo::prettyProductName(), QSysInfo::kernelType(), QSysInfo::kernelVersion());
}
QString Platform::compiler() {
QString compiler;
#ifdef Q_CC_MSVC
compiler += "Microsoft Visual C/C++, Intel C++ for Windows";
#endif
#ifdef Q_CC_GNU
compiler += "GNU C++";
#endif
#ifdef Q_CC_INTEL
return "Intel C++ for Linux, Intel C++ for Windows";
#endif
#ifdef Q_CC_CLANG
compiler += "C++ front-end for the LLVM compiler";
#endif
// https://stackoverflow.com/questions/2324658/how-to-determine-the-version-of-the-c-standard-used-by-the-compiler
#if defined(_MSVC_LANG)
#define cpluspluslevel _MSVC_LANG
#elif defined(__cplusplus)
#define cpluspluslevel __cplusplus
#else
#define cpluspluslevel 0
#endif
compiler += QString(", C++ %1").arg(cpluspluslevel);
return compiler;
}
QString Platform::compileMode() {
#ifdef QT_NO_DEBUG
return "release";
#endif
#ifdef QT_DEBUG
return "debug";
#endif
}
QString Platform::version() {
// @see QuteScoop.pro
auto describe = QString(GIT_DESCRIBE);
auto branch = QString(GIT_BRANCH);
if (branch == "master" || branch == "main" || branch.startsWith("release/")) {
return describe;
}
return describe + "-" + GIT_BRANCH;
}
| 1,326
|
C++
|
.cpp
| 46
| 25.76087
| 118
| 0.692852
|
qutescoop/qutescoop
| 33
| 15
| 21
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,634
|
Ping.cpp
|
qutescoop_qutescoop/src/Ping.cpp
|
#include "Ping.h"
void Ping::pingReadyRead() {
QRegExp findMs = QRegExp("(\\d*\\.?\\d*)\\W?ms", Qt::CaseInsensitive);
if (findMs.indexIn(_pingProcess->readAll()) > 0) {
int ping = (int) findMs.cap(1).toDouble();
emit havePing(_server, ping);
} else {
emit havePing(_server, -1);
}
}
void Ping::startPing(QString server) {
_server = server;
_pingProcess = new QProcess(this);
connect(_pingProcess, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), this, &Ping::pingReadyRead);
QStringList pingArgs;
#ifdef Q_OS_WIN
pingArgs << "-n 1" << server;
#endif
#ifdef Q_OS_LINUX
pingArgs << "-c1" << server;
#endif
#ifdef Q_OS_MAC
pingArgs << "-c1" << server;
#endif
qDebug() << "executing" << "ping" << pingArgs;
_pingProcess->start("ping", pingArgs);
}
| 838
|
C++
|
.cpp
| 27
| 27.074074
| 117
| 0.630731
|
qutescoop/qutescoop
| 33
| 15
| 21
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,635
|
GLWidget.cpp
|
qutescoop_qutescoop/src/GLWidget.cpp
|
#include "GLWidget.h"
#include "Controller.h"
#include "dialogs/AirportDetails.h"
#include "dialogs/PlanFlightDialog.h"
#include "dialogs/PilotDetails.h"
#include "GuiMessage.h"
#include "LineReader.h"
#include "NavData.h"
#include "Pilot.h"
#include "Settings.h"
#include "Waypoint.h"
#include "Whazzup.h"
//#include <GL/glext.h> // Multitexturing - not platform-independant
#include <algorithm>
GLWidget::GLWidget(QGLFormat fmt, QWidget* parent)
: QGLWidget(fmt, parent),
m_isMapMoving(false), m_isMapZooming(false), m_isMapRectSelecting(false),
_lightsGenerated(false),
_earthTex(0), _fadeOutTex(0),
_earthList(0), _coastlinesList(0), _countriesList(0), _gridlinesList(0),
_pilotsList(0), _activeAirportsList(0), _inactiveAirportsList(0),
_usedWaypointsList(0), _sectorPolygonsList(0), _sectorPolygonBorderLinesList(0),
_congestionsList(0),
_staticSectorPolygonsList(0), _staticSectorPolygonBorderLinesList(0),
_hoveredSectorPolygonsList(0), _hoveredSectorPolygonBorderLinesList(0),
_pilotLabelZoomTreshold(1.5),
_activeAirportLabelZoomTreshold(2.), _inactiveAirportLabelZoomTreshold(.12),
_controllerLabelZoomTreshold(2.5),
_usedWaypointsLabelZoomThreshold(.7),
_xRot(0), _yRot(0), _zRot(0), _zoom(2), _aspectRatio(1) {
setAutoFillBackground(false);
setMouseTracking(true);
// call default (=9) map position (without triggering a GuiMessage)
restorePosition(9, true);
clientSelection = new ClientSelectionWidget();
m_updateTimer = new QTimer(this);
connect(m_updateTimer, &QTimer::timeout, this, QOverload<>::of(&QWidget::update));
configureUpdateTimer();
m_hoverDebounceTimer = new QTimer(this);
connect(m_hoverDebounceTimer, &QTimer::timeout, this, &GLWidget::updateHoverState);
configureHoverDebounce();
}
GLWidget::~GLWidget() {
glDeleteLists(_earthList, 1); glDeleteLists(_gridlinesList, 1);
glDeleteLists(_coastlinesList, 1); glDeleteLists(_countriesList, 1);
glDeleteLists(_usedWaypointsList, 1); glDeleteLists(_pilotsList, 1);
glDeleteLists(_activeAirportsList, 1); glDeleteLists(_inactiveAirportsList, 1);
glDeleteLists(_congestionsList, 1);
glDeleteLists(_sectorPolygonsList, 1); glDeleteLists(_sectorPolygonBorderLinesList, 1);
glDeleteLists(_staticSectorPolygonsList, 1);
glDeleteLists(_staticSectorPolygonBorderLinesList, 1);
glDeleteLists(_hoveredSectorPolygonsList, 1);
glDeleteLists(_hoveredSectorPolygonBorderLinesList, 1);
if (glIsTexture(_earthTex) == GL_TRUE) {
deleteTexture(_earthTex);
//glDeleteTextures(1, &earthTex); // handled Qt'ish by deleteTexture
}
if (glIsTexture(_fadeOutTex) == GL_TRUE) {
deleteTexture(_fadeOutTex);
}
gluDeleteQuadric(_earthQuad);
delete clientSelection;
}
void GLWidget::setMapPosition(double lat, double lon, double newZoom) {
_xRot = Helpers::modPositive(270. - lat, 360.);
_zRot = Helpers::modPositive(-lon, 360.);
_zoom = newZoom;
resetZoom();
update();
}
void GLWidget::invalidatePilots() {
m_isPilotsListDirty = true;
m_isPilotMapObjectsDirty = true;
m_isUsedWaypointMapObjectsDirty = true;
update();
}
void GLWidget::invalidateAirports() {
m_isAirportsListDirty = true;
m_isAirportsMapObjectsDirty = true;
m_isUsedWaypointMapObjectsDirty = true;
update();
}
void GLWidget::invalidateControllers() {
m_isControllerListsDirty = true;
m_isControllerMapObjectsDirty = true;
update();
}
void GLWidget::setStaticSectors(QList<Sector*> sectors) {
m_staticSectors = sectors;
m_isStaticSectorListsDirty = true;
update();
}
/**
* rotate according to mouse movement
**/
void GLWidget::handleRotation(QMouseEvent*) {
// Nvidia mouse coordinates workaround (https://github.com/qutescoop/qutescoop/issues/46)
QPoint currentPos = mapFromGlobal(QCursor::pos());
const double zoomFactor = _zoom / 10.;
double dx = (currentPos.x() - _lastPos.x()) * zoomFactor;
double dy = (-currentPos.y() + _lastPos.y()) * zoomFactor;
_xRot = Helpers::modPositive(_xRot + 180., 360.) - 180.;
_xRot = qMax(-180., qMin(0., _xRot + dy));
_zRot = Helpers::modPositive(_zRot + dx + 180., 360.) - 180.;
_lastPos = currentPos;
m_fontRectangles.clear();
update();
}
/**
* Converts screen mouse coordinates into latitude/longitude of the map.
* Calculation based on Euler angles.
* @returns false if x/y is not on the globe
**/
bool GLWidget::local2latLon(int x, int y, double &lat, double &lon) const {
// 1) mouse coordinates to Cartesian coordinates of the openGL environment [-1...+1]
double xGl = (2. * x / width() - 1.) * _aspectRatio * _zoom / 2;
double zGl = (2. * y / height() - 1.) * _zoom / 2;
double yGl = sqrt(1 - (xGl * xGl) - (zGl * zGl)); // As the radius of globe is 1
if (qIsNaN(yGl)) {
return false; // mouse is not on globe
}
// 2) skew (rotation around the x-axis, where 0° means looking onto the equator)
double theta = (_xRot + 90.) * Pi180;
// 3) new cartesian coordinates, taking skew into account
double x0 = -zGl* qSin(theta) + yGl * qCos(theta);
double z0 = +zGl* qCos(theta) + yGl * qSin(theta);
double y0 = xGl;
// 4) now to lat/lon
lat = qAtan(-z0 / qSqrt(1 - (z0 * z0))) * 180 / M_PI;
lon = qAtan(-x0 / y0) * 180 / M_PI - 90;
// 5) qAtan might have lost the sign
if (xGl >= 0) {
lon += 180;
}
lon = Helpers::modPositive(lon - _zRot + 180., 360.) - 180.;
return true;
}
void GLWidget::scrollBy(int moveByX, int moveByY) {
QPair<double, double> cur = currentLatLon();
setMapPosition(
cur.first - (double) moveByY * _zoom * 6., // 6° on zoom=1
cur.second + (double) moveByX * _zoom * 6., _zoom
);
update();
}
void GLWidget::resetZoom() {
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
// clipping left/right/bottom/top/near/far
glOrtho(
-0.5 * _zoom * _aspectRatio,
+0.5 * _zoom * _aspectRatio,
+0.5 * _zoom,
-0.5 * _zoom,
8,
10
);
// or gluPerspective for perspective viewing
// gluPerspective(_zoom, _aspectRatio, 8, 10); // just for reference, if you want to try it
glMatrixMode(GL_MODELVIEW);
m_fontRectangles.clear();
}
/**
* Check if a point is visible to the current viewport
**/
bool GLWidget::latLon2local(double lat, double lon, int* px, int* py) const {
GLfloat buffer[6];
glFeedbackBuffer(6, GL_3D, buffer); // create a feedback buffer
glRenderMode(GL_FEEDBACK); // set to feedback mode
glBegin(GL_POINTS); // send a point to GL
VERTEX(lat, lon);
glEnd();
if (glRenderMode(GL_RENDER) > 0) { // if the feedback buffer size is zero, the point was clipped
if (px != 0) {
*px = (int) buffer[1];
}
if (py != 0) {
*py = height() - (int) buffer[2];
}
return true;
}
return false;
}
/*
* approximation
*/
QPair<DoublePair, DoublePair> GLWidget::shownLatLonExtent() const {
auto _currentLatLon = currentLatLon();
double _dLat = 40 * _zoom;
double _dLon = Helpers::modPositive(
NavData::pointDistanceBearing(
_currentLatLon.first,
_currentLatLon.second,
60. * _dLat * _aspectRatio,
90.
).second - _currentLatLon.second,
360.
);
return QPair<DoublePair, DoublePair>(
DoublePair(
fmod(_currentLatLon.first - _dLat, 180.),
fmod(_currentLatLon.second - _dLon, 180.)
),
DoublePair(
fmod(_currentLatLon.first + _dLat, 180.),
fmod(_currentLatLon.second + _dLon, 180.)
)
);
}
DoublePair GLWidget::currentLatLon() const {
return DoublePair(
Helpers::modPositive(-90. - _xRot + 180., 360.) - 180.,
Helpers::modPositive(-_zRot + 180., 360.) - 180.
);
}
void GLWidget::rememberPosition(int nr) {
GuiMessages::message(QString("Remembered map position %1").arg(nr));
Settings::setRememberedMapPosition(_xRot, _yRot, _zRot, _zoom, nr);
}
void GLWidget::restorePosition(int nr, bool isSilent) {
if (!isSilent) {
GuiMessages::message(QString("Recalled map position %1").arg(nr));
}
Settings::rememberedMapPosition(&_xRot, &_yRot, &_zRot, &_zoom, nr);
_xRot = Helpers::modPositive(_xRot, 360.);
_zRot = Helpers::modPositive(_zRot, 360.);
resetZoom();
update();
}
const QPair<double, double> GLWidget::sunZenith(const QDateTime &dateTime) const {
// dirtily approximating present zenith Lat/Lon (where the sun is directly above).
// scientific solution:
// http://openmap.bbn.com/svn/openmap/trunk/src/openmap/com/bbn/openmap/layer/daynight/SunPosition.java
// [sunPosition()] - that would have been at least 100 lines of code...
return QPair<double, double>(
-23. * qCos(
(double) dateTime.date().dayOfYear() /
(double) dateTime.date().daysInYear() * 2. * M_PI
),
-((double) dateTime.time().hour() +
(double) dateTime.time().minute() / 60.) * 15. - 180.
);
}
//////////////////////////////////////////////////////////////////////////////////////////
// Methods preparing displayLists
//
void GLWidget::createPilotsList() {
qDebug();
if (glIsList(_pilotsList) != GL_TRUE) {
_pilotsList = glGenLists(1);
}
glNewList(_pilotsList, GL_COMPILE);
QList<Pilot*> pilots = Whazzup::instance()->whazzupData().pilots.values();
// leader lines
if (Settings::timelineSeconds() > 0 && !qFuzzyIsNull(Settings::timeLineStrength())) {
glLineWidth(Settings::timeLineStrength());
glBegin(GL_LINES);
qglColor(Settings::leaderLineColor());
foreach (const Pilot* p, pilots) {
if (p->groundspeed < 30) {
continue;
}
if (qFuzzyIsNull(p->lat) && qFuzzyIsNull(p->lon)) {
continue;
}
VERTEX(p->lat, p->lon);
QPair<double, double> pos = p->positionInFuture(Settings::timelineSeconds());
VERTEX(pos.first, pos.second);
}
glEnd();
}
// flight paths, also for booked flights
if (m_isUsedWaypointMapObjectsDirty) {
m_usedWaypointMapObjects.clear();
foreach (Pilot* p, Whazzup::instance()->whazzupData().allPilots()) {
if (qFuzzyIsNull(p->lat) && qFuzzyIsNull(p->lon)) {
continue;
}
const bool isHovered = m_hoveredObjects.contains(p)
|| m_hoveredObjects.contains(p->depAirport())
|| m_hoveredObjects.contains(p->destAirport())
;
const bool isShowRouteDepAirport = p->depAirport() != 0 && p->depAirport()->showRoutes;
const bool isShowRouteDestAirport = p->destAirport() != 0 && p->destAirport()->showRoutes;
const bool isShowRouteAirport = isShowRouteDepAirport || isShowRouteDestAirport;
const bool isShowOverride = isHovered || isShowRouteAirport || p->showRoute;
const bool isShowOnlyImmediate = !isShowOverride && Settings::showRoutes() && Settings::onlyShowImmediateRoutePart();
const bool isShowDepToPlaneRoute = (isShowOverride || Settings::showRoutes()) && !isShowOnlyImmediate && !qFuzzyIsNull(Settings::depLineStrength());
const bool isShowPlaneToImmediateRoute = (isShowOverride || Settings::showRoutes()) && !qFuzzyIsNull(Settings::destImmediateLineStrength());
const bool isShowImmediateToDestRoute = (isShowOverride || Settings::showRoutes()) && !isShowOnlyImmediate && !qFuzzyIsNull(Settings::destLineStrength());
const bool isShowPlaneDestRoute = isShowPlaneToImmediateRoute || isShowImmediateToDestRoute;
if (!isShowDepToPlaneRoute && !isShowPlaneDestRoute) {
continue;
}
QList<Waypoint*> waypoints = p->routeWaypointsWithDepDest();
int next = p->nextPointOnRoute(waypoints);
QList<DoublePair> points; // these are the points that really get drawn
// Dep -> plane
if (isShowDepToPlaneRoute) {
for (int i = 0; i < next; i++) {
if (!m_usedWaypointMapObjects.contains(waypoints[i])) {
m_usedWaypointMapObjects.append(waypoints[i]);
}
points.append(DoublePair(waypoints[i]->lat, waypoints[i]->lon));
}
// draw to plane
points.append(DoublePair(p->lat, p->lon));
if (Settings::depLineDashed()) {
glLineStipple(3, 0xAAAA);
}
qglColor(Settings::depLineColor());
glLineWidth(Settings::depLineStrength());
glBegin(GL_LINE_STRIP);
NavData::plotGreatCirclePoints(points);
points.clear();
glEnd();
if (Settings::depLineDashed()) {
glLineStipple(1, 0xFFFF);
}
}
points.append(DoublePair(p->lat, p->lon));
// plane -> Dest
if (next >= waypoints.size() || !isShowPlaneDestRoute) {
continue;
}
// immediate
auto destImmediateNm = p->groundspeed * (Settings::destImmediateDurationMin() / 60.);
auto lastPoint = DoublePair(p->lat, p->lon);
double distanceFromPlane = 0;
int i = next;
if (isShowPlaneToImmediateRoute) {
for (; i < waypoints.size(); i++) {
double distance = NavData::distance(lastPoint.first, lastPoint.second, waypoints[i]->lat, waypoints[i]->lon);
if (distanceFromPlane + distance < destImmediateNm) {
if (!m_usedWaypointMapObjects.contains(waypoints[i])) {
m_usedWaypointMapObjects.append(waypoints[i]);
}
const auto _p = DoublePair(waypoints[i]->lat, waypoints[i]->lon);
if (!points.contains(_p)) { // very cautious for duplicates here
points.append(_p);
}
distanceFromPlane += distance;
lastPoint = DoublePair(waypoints[i]->lat, waypoints[i]->lon);
continue;
}
if (!points.contains(lastPoint)) {
points.append(lastPoint);
}
const float neededFraction = (destImmediateNm - distanceFromPlane) / qMax(distance, 1.);
const auto absoluteLast = NavData::greatCircleFraction(lastPoint.first, lastPoint.second, waypoints[i]->lat, waypoints[i]->lon, neededFraction);
if (!points.contains(absoluteLast)) {
points.append(absoluteLast);
}
break;
}
// fade out immediate route part
glPushAttrib(GL_ENABLE_BIT);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glEnable(GL_TEXTURE_1D);
glBindTexture(GL_TEXTURE_1D, _fadeOutTex);
qglColor(Settings::destImmediateLineColor());
glLineWidth(Settings::destImmediateLineStrength());
glBegin(GL_LINE_STRIP);
NavData::plotGreatCirclePoints(points);
glEnd();
glPopAttrib();
if (isShowImmediateToDestRoute) {
// fade in plane -> Dest
glPushAttrib(GL_ENABLE_BIT);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glEnable(GL_TEXTURE_1D);
glBindTexture(GL_TEXTURE_1D, _fadeOutTex);
qglColor(Settings::destLineColor());
if (Settings::destLineDashed()) {
glLineStipple(3, 0xAAAA);
}
glLineWidth(Settings::destLineStrength());
glBegin(GL_LINE_STRIP);
NavData::plotGreatCirclePoints(points, true);
glEnd();
if (Settings::destLineDashed()) {
glLineStipple(1, 0xFFFF);
}
glPopAttrib();
}
}
// rest
if (!isShowImmediateToDestRoute) {
continue;
}
while (points.size() > 1) {
points.takeFirst();
}
for (; i < waypoints.size(); i++) {
if (!m_usedWaypointMapObjects.contains(waypoints[i])) {
m_usedWaypointMapObjects.append(waypoints[i]);
}
points.append(DoublePair(waypoints[i]->lat, waypoints[i]->lon));
}
glPushAttrib(GL_ENABLE_BIT);
qglColor(Settings::destLineColor());
if (Settings::destLineDashed()) {
glLineStipple(3, 0xAAAA);
}
glLineWidth(Settings::destLineStrength());
glBegin(GL_LINE_STRIP);
NavData::plotGreatCirclePoints(points);
glEnd();
if (Settings::destLineDashed()) {
glLineStipple(1, 0xFFFF);
}
glPopAttrib();
}
m_isUsedWaypointMapObjectsDirty = false;
}
// aircraft dots
if (!qFuzzyIsNull(Settings::pilotDotSize())) {
glPointSize(Settings::pilotDotSize());
qglColor(Settings::pilotDotColor());
glBegin(GL_POINTS);
foreach (const Pilot* p, pilots) {
if (qFuzzyIsNull(p->lat) && qFuzzyIsNull(p->lon)) {
continue;
}
if (!p->isFriend()) {
VERTEX(p->lat, p->lon);
}
}
glEnd();
// friends
qglColor(Settings::friendsPilotDotColor());
glPointSize(Settings::pilotDotSize() * 1.3);
glBegin(GL_POINTS);
foreach (const Pilot* p, pilots) {
if (qFuzzyIsNull(p->lat) && qFuzzyIsNull(p->lon)) {
continue;
}
if (p->isFriend()) {
VERTEX(p->lat, p->lon);
}
}
glEnd();
}
// planned route from Flightplan Dialog (does not really belong to pilots lists, but is convenient here)
// @todo
if (PlanFlightDialog::instance(false) != 0) {
PlanFlightDialog::instance()->plotPlannedRoute();
}
glEndList();
// waypoints used in routes (dots)
if (glIsList(_usedWaypointsList) != GL_TRUE) {
_usedWaypointsList = glGenLists(1);
}
if (
Settings::showUsedWaypoints()
&& !qFuzzyIsNull(Settings::waypointsDotSize())
) {
glNewList(_usedWaypointsList, GL_COMPILE);
qglColor(Settings::waypointsDotColor());
glPointSize(Settings::waypointsDotSize());
glBegin(GL_POINTS);
foreach (const auto wp, m_usedWaypointMapObjects) {
VERTEX(wp->lat, wp->lon);
}
glEnd();
glEndList();
}
qDebug() << "-- finished";
}
void GLWidget::createAirportsList() {
qDebug();
if (glIsList(_activeAirportsList) != GL_TRUE) {
_activeAirportsList = glGenLists(1);
}
QList<Airport*> airportList = NavData::instance()->airports.values();
// inactive airports
if (glIsList(_inactiveAirportsList) != GL_TRUE) {
_inactiveAirportsList = glGenLists(1);
}
glNewList(_inactiveAirportsList, GL_COMPILE);
if (Settings::showInactiveAirports() && !qFuzzyIsNull(Settings::inactiveAirportDotSize())) {
glPointSize(Settings::inactiveAirportDotSize());
qglColor(Settings::inactiveAirportDotColor());
glBegin(GL_POINTS);
foreach (const Airport* a, airportList) {
if (!a->active) {
VERTEX(a->lat, a->lon);
}
}
glEnd();
}
glEndList();
// active airports
glNewList(_activeAirportsList, GL_COMPILE);
if (!qFuzzyIsNull(Settings::airportDotSize())) {
glPointSize(Settings::airportDotSize());
qglColor(Settings::airportDotColor());
glBegin(GL_POINTS);
foreach (const Airport* a, airportList) {
if (a->active) {
VERTEX(a->lat, a->lon);
}
}
glEnd();
// friends
glPointSize(Settings::airportDotSize() * 1.3);
qglColor(Settings::friendsAirportDotColor());
glBegin(GL_POINTS);
foreach (const Airport* a, airportList) {
if (a->active) {
foreach (const auto c, a->allControllers()) {
if (c->isFriend()) {
VERTEX(a->lat, a->lon);
break;
}
}
}
}
glEnd();
}
glEndList();
// airport congestion based on filtered traffic
if (glIsList(_congestionsList) != GL_TRUE) {
_congestionsList = glGenLists(1);
}
glNewList(_congestionsList, GL_COMPILE);
if (Settings::showAirportCongestion()) {
glPushAttrib(GL_ENABLE_BIT);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glEnable(GL_TEXTURE_1D);
glBindTexture(GL_TEXTURE_1D, _fadeOutTex);
foreach (const Airport* a, airportList) {
Q_ASSERT(a != 0);
if (!a->active) {
continue;
}
int congestion = a->congestion();
if (congestion < Settings::airportCongestionMovementsMin()) {
continue;
}
const GLdouble circle_distort = qCos(a->lat * Pi180);
if (qFuzzyIsNull(circle_distort)) {
continue;
}
const float fraction = qMin<float>(
1.,
Helpers::fraction(
Settings::airportCongestionMovementsMin(),
Settings::airportCongestionMovementsMax(),
a->congestion()
)
);
const GLfloat distanceNm = Helpers::lerp(
Settings::airportCongestionRadiusMin(),
Settings::airportCongestionRadiusMax(),
fraction
);
QList<QPair<double, double> > points;
for (int h = 0; h <= 360; h += 6) {
double x = a->lat + Nm2Deg(distanceNm) * qCos(h * Pi180);
double y = a->lon + Nm2Deg(distanceNm) / circle_distort * qSin(h * Pi180);
points.append(QPair<double, double>(x, y));
}
qglColor(
Helpers::mixColor(
Settings::airportCongestionColorMin(),
Settings::airportCongestionColorMax(),
fraction
)
);
if (Settings::showAirportCongestionGlow()) {
glBegin(GL_TRIANGLE_FAN);
glTexCoord1f(0.);
VERTEX(a->lat, a->lon);
for (int h = 0; h < points.size(); h++) {
glTexCoord1f(1.);
VERTEX(points[h].first, points[h].second);
}
glEnd();
}
if (Settings::showAirportCongestionRing()) {
glLineWidth(
Helpers::lerp(
Settings::airportCongestionBorderLineStrengthMin(),
Settings::airportCongestionBorderLineStrengthMax(),
fraction
)
);
glBegin(GL_LINE_LOOP);
for (int h = 0; h < points.size(); h++) {
glTexCoord1f(0.);
VERTEX(points[h].first, points[h].second);
}
glEnd();
// or as a Torus:
if (false) {
glBegin(GL_TRIANGLE_STRIP);
for (int h = 0; h <= 360; h += 6) {
glTexCoord1f(-1.);
VERTEX(
a->lat + Nm2Deg(distanceNm) * qCos(h * Pi180),
a->lon + Nm2Deg(distanceNm) / circle_distort * qSin(h * Pi180)
);
glTexCoord1f(1.);
VERTEX(
a->lat + Nm2Deg(distanceNm * 2) * qCos(h * Pi180),
a->lon + Nm2Deg(distanceNm * 2) / circle_distort * qSin(h * Pi180)
);
}
glEnd();
}
}
}
glPopAttrib();
}
glEndList();
qDebug() << "-- finished";
}
void GLWidget::createControllerLists() {
qDebug();
// FIR polygons
if (glIsList(_sectorPolygonsList) != GL_TRUE) {
_sectorPolygonsList = glGenLists(1);
}
auto _sectorsToDraw = Whazzup::instance()->whazzupData().controllersWithSectors();
// make sure all the lists are there to avoid nested glNewList calls
foreach (const Controller* c, _sectorsToDraw) {
if (c->sector != 0) {
c->sector->glPolygon();
}
}
// create a list of lists
glNewList(_sectorPolygonsList, GL_COMPILE);
foreach (const Controller* c, _sectorsToDraw) {
if (c->sector != 0) {
glCallList(c->sector->glPolygon());
}
}
glEndList();
// FIR borders
if (glIsList(_sectorPolygonBorderLinesList) != GL_TRUE) {
_sectorPolygonBorderLinesList = glGenLists(1);
}
if (!qFuzzyIsNull(Settings::firBorderLineStrength())) {
// first, make sure all lists are there
foreach (const Controller* c, _sectorsToDraw) {
if (c->sector != 0) {
c->sector->glBorderLine();
}
}
glNewList(_sectorPolygonBorderLinesList, GL_COMPILE);
foreach (const Controller* c, _sectorsToDraw) {
if (c->sector != 0) {
glCallList(c->sector->glBorderLine());
}
}
glEndList();
}
qDebug() << "-- finished";
}
void GLWidget::createHoveredControllersLists(const QSet<Controller*>& controllers) {
// make sure all the lists are there to avoid nested glNewList calls
foreach (Controller* c, controllers) {
if (c->sector != 0) {
c->sector->glPolygonHighlighted();
} else if (c->isAppDep()) {
foreach (const auto _a, c->airports()) {
_a->appDisplayList();
}
} else if (c->isTwr()) {
foreach (const auto _a, c->airports()) {
_a->twrDisplayList();
}
} else if (c->isGnd()) {
foreach (const auto _a, c->airports()) {
_a->gndDisplayList();
}
} else if (c->isDel()) {
foreach (const auto _a, c->airports()) {
_a->delDisplayList();
}
}
}
// create a list of lists
if (glIsList(_hoveredSectorPolygonsList) != GL_TRUE) {
_hoveredSectorPolygonsList = glGenLists(1);
}
glNewList(_hoveredSectorPolygonsList, GL_COMPILE);
foreach (Controller* c, controllers) {
if (c->sector != 0) {
glCallList(c->sector->glPolygonHighlighted());
} else if (c->isAppDep()) {
foreach (const auto _a, c->airports()) {
glCallList(_a->appDisplayList());
}
} else if (c->isTwr()) {
foreach (const auto _a, c->airports()) {
glCallList(_a->twrDisplayList());
}
} else if (c->isGnd()) {
foreach (const auto _a, c->airports()) {
glCallList(_a->gndDisplayList());
}
} else if (c->isDel()) {
foreach (const auto _a, c->airports()) {
glCallList(_a->delDisplayList());
}
}
}
glEndList();
// FIR borders
if (glIsList(_hoveredSectorPolygonBorderLinesList) != GL_TRUE) {
_hoveredSectorPolygonBorderLinesList = glGenLists(1);
}
if (!qFuzzyIsNull(Settings::firHighlightedBorderLineStrength())) {
// first, make sure all lists are there
foreach (Controller* c, controllers) {
if (c->sector != 0) {
c->sector->glBorderLineHighlighted();
}
}
glNewList(_hoveredSectorPolygonBorderLinesList, GL_COMPILE);
foreach (Controller* c, controllers) {
if (c->sector != 0) {
glCallList(c->sector->glBorderLineHighlighted());
}
}
glEndList();
}
}
void GLWidget::createStaticLists() {
// earth
qDebug() << "Generating quadric texture coordinates";
_earthQuad = gluNewQuadric();
gluQuadricTexture(_earthQuad, GL_TRUE); // prepare texture coordinates
gluQuadricDrawStyle(_earthQuad, GLU_FILL); // FILL, LINE, SILHOUETTE or POINT
gluQuadricNormals(_earthQuad, GLU_SMOOTH); // NONE, FLAT or SMOOTH
gluQuadricOrientation(_earthQuad, GLU_OUTSIDE); // GLU_INSIDE
parseTexture();
if (glIsTexture(_fadeOutTex) != GL_TRUE) {
glGenTextures(1, &_fadeOutTex);
glBindTexture(GL_TEXTURE_1D, _fadeOutTex);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
const char components = 4;
GLubyte buf[64 * components];
for (size_t i = 0; i < sizeof(buf); i += components) {
GLfloat fraction = i / (GLfloat) (sizeof(buf) - components);
GLfloat result = qPow(qCos(fraction * M_PI / 2.), 1.5); // ease in sine + slightly ease out
const GLubyte grey = 255 * result;
buf[i + 0] = 255; // rand() % 255; // for testing with rainbow
buf[i + 1] = 255; // rand() % 255;
buf[i + 2] = 255; // rand() % 255;
buf[i + 3] = grey;
}
glTexImage1D(GL_TEXTURE_1D, 0, components, sizeof(buf) / components, 0, GL_RGBA, GL_UNSIGNED_BYTE, buf);
}
_earthList = glGenLists(1);
glNewList(_earthList, GL_COMPILE);
qglColor(Settings::globeColor());
gluSphere(
_earthQuad, 1, qRound(360. / Settings::glCirclePointEach()), // draw a globe with..
qRound(180. / Settings::glCirclePointEach())
); // ..radius, slicesX, stacksZ
// drawing the sphere by hand and setting TexCoords for Multitexturing (if we need it once):
// glBegin(GL_TRIANGLE_STRIP);
// for(double lat = -90; lat <= 90 - Settings::glCirclePointEach(); lat += Settings::glCirclePointEach()) {
// for(double lon = -180; lon <= 180; lon += Settings::glCirclePointEach()) {
// GLdouble dLat = lat;
// GLdouble dLon = lon;
// for(int tmu=0; tmu < 8; tmu++)
// glMultiTexCoord2d(GL_TEXTURE0 + tmu, (dLon + 180.) / 360., (-dLat + 90.) / 180.);
// glNormal3d(SX(lat, lon), SY(lat, lon), SZ(lat, lon));
// VERTEX(dLat, dLon);
// dLat = lat + Settings::glCirclePointEach();
// for(int tmu=0; tmu < 8; tmu++)
// glMultiTexCoord2d(GL_TEXTURE0 + tmu, (dLon + 180.) / 360., (-dLat + 90.) / 180.);
// glNormal3d(SX(lat, lon), SY(lat, lon), SZ(lat, lon));
// VERTEX(dLat, dLon);
// }
// }
// glEnd();
glEndList();
// grid
qDebug() << "gridLines";
_gridlinesList = glGenLists(1);
glNewList(_gridlinesList, GL_COMPILE);
if (!qFuzzyIsNull(Settings::gridLineStrength())) {
// meridians
qglColor(Settings::gridLineColor());
glLineWidth(Settings::gridLineStrength());
for (int lon = 0; lon < 180; lon += Settings::earthGridEach()) {
glBegin(GL_LINE_LOOP);
for (int lat = 0; lat < 360; lat += Settings::glCirclePointEach()) {
VERTEX(lat, lon);
}
glEnd();
}
// parallels
for (int lat = -90 + Settings::earthGridEach(); lat < 90; lat += Settings::earthGridEach()) {
glBegin(GL_LINE_LOOP);
for (
int lon = -180; lon < 180;
lon += qCeil(Settings::glCirclePointEach() / qCos(lat * Pi180))
) {
VERTEX(lat, lon);
}
glEnd();
}
}
glEndList();
// coastlines
qDebug() << "coastLines";
_coastlinesList = glGenLists(1);
glNewList(_coastlinesList, GL_COMPILE);
if (!qFuzzyIsNull(Settings::coastLineStrength())) {
qglColor(Settings::coastLineColor());
glLineWidth(Settings::coastLineStrength());
LineReader lineReader(Settings::dataDirectory("data/coastline.dat"));
QList<QPair<double, double> > line = lineReader.readLine();
while (!line.isEmpty()) {
glBegin(GL_LINE_STRIP);
for (int i = 0; i < line.size(); i++) {
VERTEX(line[i].first, line[i].second);
}
glEnd();
line = lineReader.readLine();
}
}
glEndList();
// countries
qDebug() << "countries";
_countriesList = glGenLists(1);
glNewList(_countriesList, GL_COMPILE);
if (!qFuzzyIsNull(Settings::countryLineStrength())) {
qglColor(Settings::countryLineColor());
glLineWidth(Settings::countryLineStrength());
LineReader countries = LineReader(Settings::dataDirectory("data/countries.dat"));
QList<QPair<double, double> > line = countries.readLine();
while (!line.isEmpty()) {
glBegin(GL_LINE_STRIP);
for (int i = 0; i < line.size(); i++) {
VERTEX(line[i].first, line[i].second);
}
glEnd();
line = countries.readLine();
}
}
glEndList();
}
void GLWidget::createStaticSectorLists() {
//Polygon
if (glIsList(_staticSectorPolygonsList) != GL_TRUE) {
_staticSectorPolygonsList = glGenLists(1);
}
// make sure all the lists are there to avoid nested glNewList calls
foreach (Sector* sector, m_staticSectors) {
if (sector != 0) {
sector->glPolygon();
}
}
// create a list of lists
glNewList(_staticSectorPolygonsList, GL_COMPILE);
foreach (Sector* sector, m_staticSectors) {
if (sector != 0) {
glCallList(sector->glPolygon());
}
}
glEndList();
// FIR borders
if (glIsList(_staticSectorPolygonBorderLinesList) != GL_TRUE) {
_staticSectorPolygonBorderLinesList = glGenLists(1);
}
if (!qFuzzyIsNull(Settings::firBorderLineStrength())) {
// first, make sure all lists are there
foreach (Sector* sector, m_staticSectors) {
if (sector != 0) {
sector->glBorderLine();
}
}
glNewList(_staticSectorPolygonBorderLinesList, GL_COMPILE);
foreach (Sector* sector, m_staticSectors) {
if (sector != 0) {
glCallList(sector->glBorderLine());
}
}
glEndList();
}
}
/**
* Sets up OpenGL environment and prepares static artefacts for quick access later.
* Call drawCoordinateAxii() inside paintGL() to see where the axii are.
**/
void GLWidget::initializeGL() {
qDebug() << "OpenGL support: " << context()->format().hasOpenGL()
<< "; 1.1:" << format().openGLVersionFlags().testFlag(QGLFormat::OpenGL_Version_1_1)
<< "; 1.2:" << format().openGLVersionFlags().testFlag(QGLFormat::OpenGL_Version_1_2)
<< "; 1.3:" << format().openGLVersionFlags().testFlag(QGLFormat::OpenGL_Version_1_3) // multitexturing
<< "; 1.4:" << format().openGLVersionFlags().testFlag(QGLFormat::OpenGL_Version_1_4)
<< "; 1.5:" << format().openGLVersionFlags().testFlag(QGLFormat::OpenGL_Version_1_5)
<< "; 2.0:" << format().openGLVersionFlags().testFlag(QGLFormat::OpenGL_Version_2_0)
<< "; 2.1:" << format().openGLVersionFlags().testFlag(QGLFormat::OpenGL_Version_2_1)
<< "; 3.0:" << format().openGLVersionFlags().testFlag(QGLFormat::OpenGL_Version_3_0)
<< "; 3.1:" << format().openGLVersionFlags().testFlag(QGLFormat::OpenGL_Version_3_1)
<< "; 3.2:" << format().openGLVersionFlags().testFlag(QGLFormat::OpenGL_Version_3_2)
<< "; 3.3:" << format().openGLVersionFlags().testFlag(QGLFormat::OpenGL_Version_3_3)
<< "; 4.0:" << format().openGLVersionFlags().testFlag(QGLFormat::OpenGL_Version_4_0);
qDebug() << "GL_VENDOR: " << reinterpret_cast<char const*> (glGetString(GL_VENDOR));
qDebug() << "GL_RENDERER:" << reinterpret_cast<char const*> (glGetString(GL_RENDERER));
qDebug() << "GL_VERSION: " << reinterpret_cast<char const*> (glGetString(GL_VERSION));
qDebug() << "GL_SHADING_LANGUAGE_VERSION:"
<< reinterpret_cast<char const*> (glGetString(GL_SHADING_LANGUAGE_VERSION));
qDebug() << "GL_EXTENSIONS:" << reinterpret_cast<char const*> (glGetString(GL_EXTENSIONS));
if (format().sampleBuffers() && format().samples() > 1) {
glEnable(GL_MULTISAMPLE);
qDebug() << "MSAA: Multi-sample anti-aliasing enabled using" << format().samples() << "sample buffers";
} else {
qWarning() << "MSAA: Multi-sample anti-aliasing has NOT been enabled. Things won't look so nice.";
}
qglClearColor(Settings::backgroundColor());
if (Settings::glStippleLines()) {
glEnable(GL_LINE_STIPPLE);
} else {
glDisable(GL_LINE_STIPPLE);
}
if (Settings::displaySmoothDots()) {
glEnable(GL_POINT_SMOOTH);
glHint(GL_POINT_SMOOTH_HINT, GL_NICEST); // GL_FASTEST, GL_NICEST, GL_DONT_CARE
} else {
glDisable(GL_POINT_SMOOTH);
glHint(GL_POINT_SMOOTH_HINT, GL_FASTEST); // GL_FASTEST, GL_NICEST, GL_DONT_CARE
}
if (Settings::displaySmoothLines()) {
glEnable(GL_LINE_SMOOTH);
glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); // GL_FASTEST, GL_NICEST, GL_DONT_CARE
} else {
glDisable(GL_LINE_SMOOTH);
glHint(GL_LINE_SMOOTH_HINT, GL_FASTEST); // GL_FASTEST, GL_NICEST, GL_DONT_CARE
}
if (Settings::glBlending()) {
glEnable(GL_BLEND);
//glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); // for texture blending
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // source,dest:
// ...GL_ZERO, GL_ONE, GL_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR, GL_DST_COLOR, GL_ONE_MINUS_DST_COLOR,
// ...GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA, GL_CONSTANT_COLOR,
// ...GL_ONE_MINUS_CONSTANT_COLOR, GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA, GL_SRC_ALPHA_SATURATE
glEnable(GL_FOG); // fog - fading Earth's borders
glFogi(GL_FOG_MODE, GL_LINEAR); // GL_EXP2, GL_EXP, GL_LINEAR
GLfloat fogColor[] = {
(GLfloat) Settings::backgroundColor().redF(),
(GLfloat) Settings::backgroundColor().greenF(),
(GLfloat) Settings::backgroundColor().blueF(),
(GLfloat) Settings::backgroundColor().alphaF()
};
glFogfv(GL_FOG_COLOR, fogColor);
glFogf(GL_FOG_DENSITY, 1.);
glHint(GL_FOG_HINT, GL_DONT_CARE);
glFogf(GL_FOG_START, (GLfloat) 9.8);
glFogf(GL_FOG_END, 10.);
} else {
glBlendFunc(GL_ONE, GL_ZERO);
glDisable(GL_BLEND);
glDisable(GL_FOG);
}
glDisable(GL_DEPTH_TEST); // this helps against sectors and coastlines that..
//are "farer" away than the earth superficie
// - also we do not need that. We just draw from far to near...
//glDepthFunc(GL_LEQUAL); // when using DEPTH_TEST
//glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // 1st: GL_FOG_HINT, GL_GENERATE_MIPMAP_HINT,
// ...GL_LINE_SMOOTH_HINT, GL_PERSPECTIVE_CORRECTION_HINT, GL_POINT_SMOOTH_HINT,
// ...GL_POLYGON_SMOOTH_HINT, GL_TEXTURE_COMPRESSION_HINT, GL_FRAGMENT_SHADER_DERIVATIVE_HINT
// ...2nd: GL_FASTEST, GL_NICEST, GL_DONT_CARE
/* OpenGL lighting
* AMBIENT - light that comes from all directions equally and is scattered in all directions equally by the
* polygons
* in your scene. This isn't quite true of the real world - but it's a good first approximation for light that
* comes
* pretty much uniformly from the sky and arrives onto a surface by bouncing off so many other surfaces that it
* might
* as well be uniform.
* DIFFUSE - light that comes from a particular point source (like the Sun) and hits surfaces with an intensity
* that depends on whether they face towards the light or away from it. However, once the light radiates from
* the
* surface, it does so equally in all directions. It is diffuse lighting that best defines the shape of 3D
* objects.
* SPECULAR - as with diffuse lighting, the light comes from a point souce, but with specular lighting, it is
* reflected
* more in the manner of a mirror where most of the light bounces off in a particular direction defined by the
* surface
* shape. Specular lighting is what produces the shiney highlights and helps us to distinguish between flat,
* dull
* surfaces such as plaster and shiney surfaces like polished plastics and metals.
* EMISSION - in this case, the light is actually emitted by the polygon - equally in all directions.
* */
if (Settings::glLighting()) {
//const GLfloat earthAmbient[] = {0, 0, 0, 1};
const GLfloat earthDiffuse[] = { 1, 1, 1, 1 };
const GLfloat earthSpecular[] = {
(GLfloat) Settings::specularColor().redF(),
(GLfloat) Settings::specularColor().greenF(),
(GLfloat) Settings::specularColor().blueF(),
(GLfloat) Settings::specularColor().alphaF()
};
const GLfloat earthEmission[] = { 0, 0, 0, 1 };
const GLfloat earthShininess[] = { (GLfloat) Settings::earthShininess() };
//glMaterialfv(GL_FRONT, GL_AMBIENT, earthAmbient); // GL_AMBIENT, GL_DIFFUSE, GL_SPECULAR,
glMaterialfv(GL_FRONT, GL_DIFFUSE, earthDiffuse); // ...GL_EMISSION, GL_SHININESS,
// GL_AMBIENT_AND_DIFFUSE,
glMaterialfv(GL_FRONT, GL_SPECULAR, earthSpecular); // ...GL_COLOR_INDEXES
glMaterialfv(GL_FRONT, GL_EMISSION, earthEmission); //
glMaterialfv(GL_FRONT, GL_SHININESS, earthShininess); //... only DIFFUSE has an own alpha channel!
glColorMaterial(GL_FRONT, GL_AMBIENT); // GL_EMISSION, GL_AMBIENT, GL_DIFFUSE, GL_SPECULAR,
// GL_AMBIENT_AND_DIFFUSE
glEnable(GL_COLOR_MATERIAL); // controls if glColor will drive the given values in glColorMaterial
const GLfloat sunAmbient[] = { 0., 0., 0., 1. };
QColor adjustSunDiffuse = Settings::sunLightColor();
if (Settings::glLights() > 1) {
adjustSunDiffuse = adjustSunDiffuse.darker(
100. * (Settings::glLights() - // reduce light intensity
// by number of lights...
Settings::glLightsSpread() / 180. *
(Settings::glLights() - 1))
); // ...and increase again
}
// by their distribution
const GLfloat sunDiffuse[] = {
(GLfloat) adjustSunDiffuse.redF(),
(GLfloat) adjustSunDiffuse.greenF(),
(GLfloat) adjustSunDiffuse.blueF(),
(GLfloat) adjustSunDiffuse.alphaF()
};
//const GLfloat sunSpecular[] = {1, 1, 1, 1}; // we drive this via material values
for (int light = 0; light < 8; light++) {
if (light < Settings::glLights()) {
glLightfv(GL_LIGHT0 + light, GL_AMBIENT, sunAmbient); // GL_AMBIENT, GL_DIFFUSE,
// GL_SPECULAR, GL_POSITION, GL_SPOT_CUTOFF,
glLightfv(GL_LIGHT0 + light, GL_DIFFUSE, sunDiffuse); // ...GL_SPOT_DIRECTION,
// GL_SPOT_EXPONENT,
// GL_CONSTANT_ATTENUATION,
//glLightfv(GL_LIGHT0 + light, GL_SPECULAR, sunSpecular);// ...GL_LINEAR_ATTENUATION
// GL_QUADRATIC_ATTENUATION
glEnable(GL_LIGHT0 + light);
} else {
glDisable(GL_LIGHT0 + light);
}
}
const GLfloat modelAmbient[] = { (GLfloat) .2, (GLfloat) .2, (GLfloat) .2, (GLfloat) 1. }; // the
// "background"
// ambient
// light
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, modelAmbient); // GL_LIGHT_MODEL_AMBIENT,
// GL_LIGHT_MODEL_COLOR_CONTROL,
//glLightModelf(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE); // ...GL_LIGHT_MODEL_LOCAL_VIEWER,
// GL_LIGHT_MODEL_TWO_SIDE
glShadeModel(GL_SMOOTH); // SMOOTH or FLAT
glEnable(GL_NORMALIZE);
_lightsGenerated = true;
}
createStaticLists();
qDebug() << "-- finished";
}
/**
* gets called whenever a screen refresh is needed. If you want to schedule a repaint,
* call update().
*/
void GLWidget::paintGL() {
qint64 started = QDateTime::currentMSecsSinceEpoch(); // for method execution time calculation.
// create lists (if necessary)
if (m_isPilotsListDirty) {
createPilotsList();
m_isPilotsListDirty = false;
}
if (m_isControllerListsDirty) {
createControllerLists();
m_isControllerListsDirty = false;
}
if (m_isAirportsListDirty) {
createAirportsList();
m_isAirportsListDirty = false;
}
if (m_isStaticSectorListsDirty) {
createStaticSectorLists();
m_isStaticSectorListsDirty = false;
}
createHoveredControllersLists(m_hoveredControllers);
// blank out the screen (buffered, of course)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glTranslatef(0, 0, -10);
glRotated(_xRot, 1, 0, 0);
glRotated(_yRot, 0, 1, 0);
glRotated(_zRot, 0, 0, 1);
if (Settings::glLighting()) {
if (!_lightsGenerated) {
createLights();
}
glEnable(GL_LIGHTING);
// moving sun's position
QPair<double, double> zenith = sunZenith(
Whazzup::instance()->whazzupData().whazzupTime.isValid()?
Whazzup::instance()->whazzupData().whazzupTime:
QDateTime::currentDateTimeUtc()
);
GLfloat sunVertex0[] = { SX(zenith.first, zenith.second), SY(zenith.first, zenith.second),
SZ(zenith.first, zenith.second), 0 }; // sun has parallel light -> dist=0
glLightfv(GL_LIGHT0, GL_POSITION, sunVertex0); // light 0 always has the real (center) position
if (Settings::glLights() > 1) {
for (int light = 1; light < Settings::glLights(); light++) { // setting the other lights'
// positions
double fraction = 2 * M_PI / (Settings::glLights() - 1) * light;
double spreadLat = zenith.first + qSin(fraction) * Settings::glLightsSpread();
double spreadLon = zenith.second + qCos(fraction) * Settings::glLightsSpread();
GLfloat sunVertex[] = { SX(spreadLat, spreadLon), SY(spreadLat, spreadLon), SZ(spreadLat, spreadLon), 0 };
glLightfv(GL_LIGHT0 + light, GL_POSITION, sunVertex); // GL_LIGHTn is conveniently
// GL_LIGHT0 + n
}
}
}
if (Settings::glTextures() && glIsTexture(_earthTex) == GL_TRUE) {
glEnable(GL_TEXTURE_2D);
if (Settings::glLighting()) {
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); // GL_MODULATE, GL_DECAL, GL_BLEND,
// GL_REPLACE
} else {
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
}
glBindTexture(GL_TEXTURE_2D, _earthTex);
}
glCallList(_earthList);
if (Settings::glLighting()) {
glDisable(GL_LIGHTING); // disable lighting after drawing earth...
}
if (Settings::glTextures() && glIsTexture(_earthTex) == GL_TRUE) { // disable textures after drawing earth...
glDisable(GL_TEXTURE_2D);
}
glCallList(_coastlinesList);
glCallList(_countriesList);
glCallList(_gridlinesList);
if (Settings::showUsedWaypoints() && _zoom < _usedWaypointsLabelZoomThreshold * .1) {
glCallList(_usedWaypointsList);
}
// render sectors
if (Settings::showCTR()) {
glCallList(_sectorPolygonsList);
glCallList(_sectorPolygonBorderLinesList);
}
if (Settings::showAirportCongestion()) {
glCallList(_congestionsList);
}
// render hovered sectors
if (m_hoveredControllers.size() > 0) {
glCallList(_hoveredSectorPolygonsList);
glCallList(_hoveredSectorPolygonBorderLinesList);
}
// render sectors independently from Whazzup
if (m_staticSectors.size() > 0) {
glCallList(_staticSectorPolygonsList);
glCallList(_staticSectorPolygonBorderLinesList);
}
QList<Airport*> airportList = NavData::instance()->airports.values();
// render Approach
if (Settings::showAPP()) {
foreach (Airport* a, airportList) {
if (!a->appDeps.isEmpty()) {
glCallList(a->appDisplayList());
}
}
}
// render Tower
if (Settings::showTWR()) {
foreach (Airport* a, airportList) {
if (!a->twrs.isEmpty()) {
glCallList(a->twrDisplayList());
}
}
}
// render Ground/Delivery
if (Settings::showGND()) {
foreach (Airport* a, airportList) {
if (!a->dels.isEmpty()) {
glCallList(a->delDisplayList());
}
if (!a->gnds.isEmpty()) {
glCallList(a->gndDisplayList());
}
}
}
glCallList(_activeAirportsList);
if (Settings::showInactiveAirports() && (_zoom < _inactiveAirportLabelZoomTreshold * .2)) {
// show inactive airport dot only when zoomed in a lot
glCallList(_inactiveAirportsList);
}
// render pilots
glCallList(_pilotsList);
// highlight friends
if (Settings::highlightFriends()) {
double dRange = 0;
if (Settings::animateFriendsHighlight()) {
dRange = qSin(QTime::currentTime().msec() / 1000. * M_PI);
}
double lineWidth = Settings::highlightLineWidth();
foreach (const auto &_friend, m_friendPositions) {
if (qFuzzyIsNull(_friend.first) && qFuzzyIsNull(_friend.second)) {
continue;
}
glLineWidth(lineWidth);
qglColor(Settings::friendsHighlightColor());
glBegin(GL_LINE_LOOP);
GLdouble circle_distort = qCos(_friend.first * Pi180);
for (int i = 0; i <= 360; i += 10) {
double x = _friend.first + Nm2Deg((80 - (dRange * 20))) * circle_distort * qCos(i * Pi180);
double y = _friend.second + Nm2Deg((80 - (dRange * 20))) * qSin(i * Pi180);
VERTEX(x, y);
}
glEnd();
}
}
// render labels
renderLabels();
// selection rectangle
if (m_isMapRectSelecting) {
drawSelectionRectangle();
}
// some preparations to draw textures (symbols, ...).
// drawTestTextures();
// drawCoordinateAxii(); // debug: see axii (x = red, y = green, z = blue)
if (Settings::showFps()) {
static bool _frameToggle = false;
_frameToggle = !_frameToggle;
const float _ms = QDateTime::currentMSecsSinceEpoch() - started;
const float _fps = 1000. / (QDateTime::currentMSecsSinceEpoch() - started);
qglColor(Settings::firFontColor());
renderText(
0,
height() - 2,
QString("%1 fps (%2 ms) %3").arg(_fps, 0, 'f', 0)
.arg(_ms, 0, 'i', 0)
.arg(_frameToggle? '*': ' '),
Settings::firFont()
);
}
glFlush(); // http://www.opengl.org/sdk/docs/man/xhtml/glFlush.xml
}
void GLWidget::resizeGL(int width, int height) {
_aspectRatio = (double) width / (double) height;
glViewport(0, 0, width, height);
resetZoom();
}
////////////////////////////////////////////////////////////
// SLOTS: mouse, key... and general user-map interaction
//
void GLWidget::mouseMoveEvent(QMouseEvent* event) {
// Nvidia mouse coordinates workaround (https://github.com/qutescoop/qutescoop/issues/46)
QPoint currentPos = mapFromGlobal(QCursor::pos());
if (
event->buttons().testFlag(Qt::RightButton) // check before left button if useSelectionRectangle=off
|| (!Settings::useSelectionRectangle() && event->buttons().testFlag(Qt::LeftButton))
) { // rotate
m_isMapMoving = true;
handleRotation(event);
} else if (event->buttons().testFlag(Qt::MiddleButton)) { // zoom
m_isMapZooming = true;
zoomIn((currentPos.x() - _lastPos.x() - currentPos.y() + _lastPos.y()) / 100. * Settings::zoomFactor());
_lastPos = currentPos;
} else if (event->buttons().testFlag(Qt::LeftButton)) { // selection rectangle
m_isMapRectSelecting = true;
update();
}
// suppress while doing map actions
if (!m_isMapMoving && !m_isMapZooming && !m_isMapRectSelecting) {
m_newHoveredObjects = objectsAt(currentPos.x(), currentPos.y());
}
// deal with mouseLeave immediately
auto _tmpHoveredObjects = QList<MapObject*>(m_hoveredObjects);
bool _hoveredObjectsDirty = false;
foreach (const auto &o, _tmpHoveredObjects) {
if (!m_newHoveredObjects.contains(o)) {
foreach (const auto &fr, m_fontRectangles) {
if (fr.object == o) {
m_fontRectangles.remove(fr);
m_hoveredObjects.removeOne(o);
_hoveredObjectsDirty = true;
break;
}
}
}
}
if (_hoveredObjectsDirty) {
invalidatePilots(); // for hovered objects' routes
update();
}
// deal with everything else later
if (m_newHoveredObjects != m_hoveredObjects) {
m_hoverDebounceTimer->start(); // restart timer
}
// cursor
bool hasPrimaryFunction = false;
foreach (const auto &o, m_newHoveredObjects) {
if (o->hasPrimaryAction()) {
hasPrimaryFunction = true;
break;
}
}
setCursor(hasPrimaryFunction? Qt::PointingHandCursor: Qt::ArrowCursor);
// sectors, airport controllers
double lat, lon;
if (local2latLon(currentPos.x(), currentPos.y(), lat, lon)) {
QSet<Controller*> _newHoveredControllers;
// copy from hovered map labels
foreach (const auto &o, m_newHoveredObjects) {
auto* c = dynamic_cast<Controller*>(o);
if (c != 0 && c->sector != nullptr) {
_newHoveredControllers.insert(c);
}
}
// add sectors if not currently hovering a label
if (_newHoveredControllers.isEmpty()) {
foreach (Controller* c, Whazzup::instance()->whazzupData().controllers.values()) {
if (c->sector != nullptr && c->sector->containsPoint(QPointF(lat, lon))) {
_newHoveredControllers.insert(c);
} else { // APP, TWR, GND, DEL
int maxDist_nm = -1;
if (c->isAppDep()) {
maxDist_nm = Airport::symbologyAppRadius_nm;
} else if (c->isTwr()) {
maxDist_nm = Airport::symbologyTwrRadius_nm;
} else if (c->isGnd()) {
maxDist_nm = Airport::symbologyGndRadius_nm;
} else if (c->isDel()) {
maxDist_nm = Airport::symbologyDelRadius_nm;
}
foreach (const auto _a, c->airports()) {
if (NavData::distance(_a->lat, _a->lon, lat, lon) < maxDist_nm) {
_newHoveredControllers.insert(c);
}
}
}
}
}
if (_newHoveredControllers != m_hoveredControllers) {
m_hoveredControllers = _newHoveredControllers;
invalidateControllers();
update();
}
}
}
void GLWidget::mousePressEvent(QMouseEvent*) {
// Nvidia mouse coordinates workaround (https://github.com/qutescoop/qutescoop/issues/46)
QPoint currentPos = mapFromGlobal(QCursor::pos());
QToolTip::hideText();
if (m_isMapMoving || m_isMapZooming || m_isMapRectSelecting) {
m_isMapMoving = false;
m_isMapZooming = false;
m_isMapRectSelecting = false;
update();
}
if (!m_isMapRectSelecting) {
_lastPos = _mouseDownPos = currentPos;
}
}
void GLWidget::mouseReleaseEvent(QMouseEvent* event) {
// Nvidia mouse coordinates workaround (https://github.com/qutescoop/qutescoop/issues/46)
QPoint currentPos = mapFromGlobal(QCursor::pos());
QToolTip::hideText();
if (m_isMapMoving) {
m_isMapMoving = false;
} else if (m_isMapZooming) {
m_isMapZooming = false;
} else if (m_isMapRectSelecting) {
m_isMapRectSelecting = false;
if (currentPos != _mouseDownPos) {
// moved more than 40px?
if (
((currentPos.x() - _mouseDownPos.x()) * (currentPos.x() - _mouseDownPos.x()))
+ ((currentPos.y() - _mouseDownPos.y()) * (currentPos.y() - _mouseDownPos.y())) > 40 * 40
) {
double downLat, downLon;
if (local2latLon(_mouseDownPos.x(), _mouseDownPos.y(), downLat, downLon)) {
double currLat, currLon;
if (local2latLon(currentPos.x(), currentPos.y(), currLat, currLon)) {
DoublePair mid = NavData::greatCircleFraction(downLat, downLon, currLat, currLon, .5);
setMapPosition(
mid.first, mid.second,
qMax(
NavData::distance(
downLat, downLon,
downLat, currLon
),
NavData::distance(
downLat, downLon,
currLat, downLon
)
) / 4000.
);
}
}
}
} else {
update();
}
} else if (_mouseDownPos == currentPos && event->button() == Qt::LeftButton) {
QList<MapObject*> objects;
foreach (MapObject* m, objectsAt(currentPos.x(), currentPos.y())) {
if (!m->hasPrimaryAction()) {
continue;
}
objects.append(m);
}
if (objects.isEmpty()) {
clientSelection->clearObjects();
clientSelection->close();
} else if (objects.size() == 1) {
if (objects[0]->hasPrimaryAction()) {
objects[0]->primaryAction();
}
} else {
clientSelection->move(QCursor::pos());
clientSelection->setObjects(objects);
}
} else if (_mouseDownPos == currentPos && event->button() == Qt::RightButton) {
rightClick(currentPos);
}
mouseMoveEvent(event); // handle inihibited update of hovered objects
update();
}
void GLWidget::rightClick(const QPoint& pos) {
auto objects = objectsAt(pos.x(), pos.y());
int countRelevant = 0;
Pilot* pilot = 0;
Airport* airport = 0;
foreach (MapObject* m, objects) {
if (dynamic_cast<Pilot*>(m) != 0) {
pilot = dynamic_cast<Pilot*>(m);
countRelevant++;
}
if (dynamic_cast<Airport*>(m) != 0) {
airport = dynamic_cast<Airport*>(m);
countRelevant++;
break; // priorise airports
}
}
if (countRelevant == 0) {
GuiMessages::message("no object under cursor");
} else if (countRelevant > 1) {
GuiMessages::message("too many objects under cursor");
} else if (airport != 0) {
GuiMessages::message(
QString("toggled routes for %1 [%2]").arg(airport->id, airport->showRoutes? "off": "on"),
"routeToggleAirport"
);
airport->showRoutes = !airport->showRoutes;
if (AirportDetails::instance(false) != 0) {
AirportDetails::instance()->refresh();
}
if (PilotDetails::instance(false) != 0) { // can have an effect on the state of
PilotDetails::instance()->refresh(); // ...PilotDetails::cbPlotRoutes
}
invalidatePilots();
} else if (pilot != 0) {
// display flight path for pilot
GuiMessages::message(
QString("toggled route for %1 [%2]").arg(pilot->callsign, pilot->showRoute? "off": "on"),
"routeTogglePilot"
);
pilot->showRoute = !pilot->showRoute;
if (PilotDetails::instance(false) != 0) {
PilotDetails::instance()->refresh();
}
invalidatePilots();
}
}
void GLWidget::mouseDoubleClickEvent(QMouseEvent* event) {
// Nvidia mouse coordinates workaround (https://github.com/qutescoop/qutescoop/issues/46)
QPoint currentPos = mapFromGlobal(QCursor::pos());
QToolTip::hideText();
if (event->buttons().testFlag(Qt::LeftButton)) {
double lat, lon;
if (local2latLon(currentPos.x(), currentPos.y(), lat, lon)) {
setMapPosition(lat, lon, _zoom);
}
zoomIn(.6);
} else if (event->button() == Qt::RightButton) {
double lat, lon;
if (local2latLon(currentPos.x(), currentPos.y(), lat, lon)) {
setMapPosition(lat, lon, _zoom);
}
zoomIn(-.6);
} else if (event->button() == Qt::MiddleButton) {
zoomTo(2.);
}
}
void GLWidget::wheelEvent(QWheelEvent* event) {
QToolTip::hideText();
//if(event->orientation() == Qt::Vertical) {
if (qAbs(event->angleDelta().y()) > Settings::wheelMax()) { // always recalibrate if bigger values are found
Settings::setWheelMax(qAbs(event->angleDelta().y()));
}
zoomIn((double) event->angleDelta().y() / Settings::wheelMax());
}
void GLWidget::leaveEvent(QEvent* event) {
QWidget::leaveEvent(event);
setCursor(Qt::ArrowCursor);
}
bool GLWidget::event(QEvent* event) {
// we are experimenting to not use tooltips by default currently
if (Settings::showToolTips() && event->type() == QEvent::ToolTip) {
QHelpEvent* helpEvent = static_cast<QHelpEvent*>(event);
if (m_hoveredObjects.isEmpty()) {
QToolTip::hideText();
} else {
QStringList toolTip;
foreach (const auto o, m_hoveredObjects) {
toolTip << o->toolTip();
}
QToolTip::showText(helpEvent->globalPos(), toolTip.join("\n"));
}
}
return QGLWidget::event(event);
}
void GLWidget::zoomIn(double factor) {
_zoom -= _zoom * qMax(-.6, qMin(.6, .2 * factor * Settings::zoomFactor()));
resetZoom();
update();
}
void GLWidget::zoomTo(double zoom) {
this->_zoom = zoom;
resetZoom();
update();
}
/////////////////////////////
// rendering text
/////////////////////////////
void GLWidget::renderLabels() {
/**
* Gather MapObjects
*/
// sector controller labels
if (m_isControllerMapObjectsDirty) {
qDebug() << "building controllerMapObjects";
m_controllerMapObjects.clear();
foreach (Controller* c, Whazzup::instance()->whazzupData().controllers) {
if (c->sector != 0) {
m_controllerMapObjects.append(c);
}
}
m_isControllerMapObjectsDirty = false;
}
// planned route waypoint labels from Flightplan Dialog
QList<MapObject*> planFlightWaypointMapObjects;
if (PlanFlightDialog::instance(false) != 0) {
if (
PlanFlightDialog::instance()->cbPlot->isChecked()
&& PlanFlightDialog::instance()->selectedRoute != 0
) {
for (int i = 1; i < PlanFlightDialog::instance()->selectedRoute->waypoints.size() - 1; i++) {
auto _wp = PlanFlightDialog::instance()->selectedRoute->waypoints[i];
if (!planFlightWaypointMapObjects.contains(_wp)) {
planFlightWaypointMapObjects.append(_wp);
}
}
}
}
// airport labels
if (m_isAirportsMapObjectsDirty) {
qDebug() << "building airportMapObjects";
m_activeAirportMapObjects.clear();
const QList<Airport*> activeAirportsSorted = NavData::instance()->activeAirports.values();
for (int i = activeAirportsSorted.size() - 1; i > -1; i--) { // by traffic
if (activeAirportsSorted[i]->active) {
m_activeAirportMapObjects.append(activeAirportsSorted[i]);
}
}
m_inactiveAirportMapObjectsByLatLng.clear();
if (Settings::showInactiveAirports()) {
foreach (const auto a, NavData::instance()->airports) {
if (!a->active) {
QPair<int, int> _tile(a->lat, a->lon);
m_inactiveAirportMapObjectsByLatLng.insert(_tile, a);
}
}
}
m_isAirportsMapObjectsDirty = false;
}
// partition inactive airports (each frame)
QList<MapObject*> _inactiveAirportMapObjectsFiltered;
if (Settings::showInactiveAirports() && _zoom <= _inactiveAirportLabelZoomTreshold) {
auto _extent = shownLatLonExtent();
for (int _lat = floor(_extent.first.first); _lat <= ceil(_extent.second.first); _lat++) {
for (int _lon = floor(_extent.first.second); _lon <= ceil(_extent.second.second); _lon++) {
_inactiveAirportMapObjectsFiltered += m_inactiveAirportMapObjectsByLatLng.values(
QPair<int, int>(_lat, _lon)
);
}
}
// produce a random, but stable distribution
std::sort(
_inactiveAirportMapObjectsFiltered.begin(),
_inactiveAirportMapObjectsFiltered.end(),
[](MapObject* a, MapObject* b) {
return QCryptographicHash::hash(((Airport*) a)->id.toLatin1(), QCryptographicHash::Md5)
> QCryptographicHash::hash(((Airport*) b)->id.toLatin1(), QCryptographicHash::Md5);
}
);
}
// pilot labels
if (m_isPilotMapObjectsDirty) {
qDebug() << "building pilotMapObjects";
m_pilotMapObjects.clear();
const QList<Pilot*> pilots = Whazzup::instance()->whazzupData().allPilots();
if (Settings::showPilotsLabels()) {
foreach (Pilot* p, pilots) {
if (qFuzzyIsNull(p->lat) && qFuzzyIsNull(p->lon)) {
continue;
}
if (
p->flightStatus() == Pilot::DEPARTING
|| p->flightStatus() == Pilot::EN_ROUTE
|| p->flightStatus() == Pilot::ARRIVING
) {
if (p->isFriend()) {
m_pilotMapObjects.prepend(p);
} else {
m_pilotMapObjects.append(p);
}
}
}
}
m_isPilotMapObjectsDirty = false;
}
// labels of waypoints used in shown routes
// - we build that list in createPilotsList() now
/**
* remove vanished MapObjects from m_fontRectangles to keep positions as sticky as possible
*/
const QList<MapObject*> allMapObjects =
m_controllerMapObjects // big hover area makes it difficult to hover other labels
+ planFlightWaypointMapObjects
+ m_activeAirportMapObjects
+ m_pilotMapObjects
+ m_usedWaypointMapObjects
+ _inactiveAirportMapObjectsFiltered // that might hit performance
;
// update our list of stable positions
foreach (const auto &fr, m_fontRectangles) {
if (!allMapObjects.contains(fr.object)) {
m_fontRectangles.remove(fr);
}
}
/**
* Render labels
*/
// sector controller labels
renderLabels(
m_controllerMapObjects,
_controllerLabelZoomTreshold,
Settings::firFont(),
Settings::firFontColor(),
Settings::firFontSecondary(),
Settings::firFontSecondaryColor(),
false,
99 // try many secondary positions
);
// static sectors - render directly, no questions asked
qglColor(Settings::friendsHighlightColor()); // just something different from normal sectors
foreach (const Sector* sector, m_staticSectors) {
QPair<double, double> center = sector->getCenter();
if (center.first > -180.) {
double lat = center.first;
double lon = center.second;
renderText(
SX(lat, lon),
SY(lat, lon),
SZ(lat, lon),
sector->icao,
Settings::firFont()
);
}
}
// planned route waypoint labels from Flightplan Dialog
renderLabels(
planFlightWaypointMapObjects,
_usedWaypointsLabelZoomThreshold,
Settings::waypointsFont(),
Settings::waypointsFontColor(),
Settings::waypointsFont(),
Settings::waypointsFontColor()
);
// airport labels
renderLabels(
m_activeAirportMapObjects,
_activeAirportLabelZoomTreshold,
Settings::airportFont(),
Settings::airportFontColor(),
Settings::airportFontSecondary(),
Settings::airportFontSecondaryColor()
);
// pilot labels
renderLabels(
m_pilotMapObjects,
_pilotLabelZoomTreshold,
Settings::pilotFont(),
Settings::pilotFontColor(),
Settings::pilotFontSecondary(),
Settings::pilotFontSecondaryColor()
);
// waypoints used in shown routes
if (Settings::showUsedWaypoints()) {
renderLabels(
m_usedWaypointMapObjects,
_usedWaypointsLabelZoomThreshold,
Settings::waypointsFont(),
Settings::waypointsFontColor(),
Settings::waypointsFont(),
Settings::waypointsFontColor(),
false, // fast bail
0 // don't try secondary positions
);
}
// inactive airports
if (Settings::showInactiveAirports()) {
renderLabels(
_inactiveAirportMapObjectsFiltered,
_inactiveAirportLabelZoomTreshold,
Settings::inactiveAirportFont(),
Settings::inactiveAirportFontColor(),
Settings::airportFontSecondary(),
Settings::airportFontSecondaryColor()
);
}
// last (but always rendered): hovered objects
foreach (const auto renderLabelCommand, m_prioritizedLabels) {
renderLabels(
renderLabelCommand.objects,
renderLabelCommand.zoomTreshold,
renderLabelCommand.font,
renderLabelCommand.color,
renderLabelCommand.secondaryFont,
renderLabelCommand.secondaryColor,
renderLabelCommand.isFastBail,
renderLabelCommand.tryNOtherPositions,
true
);
}
m_prioritizedLabels.clear();
}
void GLWidget::renderLabels(
const QList<MapObject*>& objects,
const double zoomTreshold,
const QFont& font,
const QColor _color,
const QFont& secondaryFont,
const QColor _secondaryColor,
const bool isFastBail, // performance optimization: bail on first MapObject that's not drawn - this will not work if
// stable positions are desired
const unsigned short tryNOtherPositions,
const bool isHoverRenderPass
) {
if (_zoom > zoomTreshold || _color.alpha() == 0) {
return;
}
QFontMetricsF fontMetrics(font, this);
QFontMetricsF fontMetricsSecondary(secondaryFont, this);
foreach (MapObject* o, objects) {
int x, y;
if (!latLon2local(o->lat, o->lon, &x, &y)) {
continue;
}
Controller* c = dynamic_cast<Controller*>(o);
bool isHoveredSector = c != 0 && m_hoveredControllers.contains(c);
const bool isHovered = m_hoveredObjects.contains(o)
&& !m_isMapMoving && !m_isMapRectSelecting && !m_isMapZooming;
// fade out
auto color(_color);
auto secondaryColor(_secondaryColor);
if (!isHovered) {
color.setAlphaF(qMax(0., qMin(color.alphaF(), (zoomTreshold - _zoom) / zoomTreshold * 1.5)));
secondaryColor.setAlphaF(qMax(0., qMin(secondaryColor.alphaF(), (zoomTreshold - _zoom) / zoomTreshold * 1.5)));
}
// if it is hovered, save for the hoverRenderPass later
if (isHovered && !isHoverRenderPass) {
m_prioritizedLabels.prepend(
{
{ o },
zoomTreshold,
font,
color,
secondaryFont,
secondaryColor,
isFastBail,
tryNOtherPositions
}
);
continue;
}
if (Settings::onlyShowHoveredLabels() && !isHoverRenderPass) {
continue;
}
FontRectangle useRect;
// look if we have previously drawn that label
foreach (const auto &fr, m_fontRectangles) {
if (fr.object == o) {
useRect = fr;
m_fontRectangles.remove(fr);
break;
}
}
if (
!isHovered
&& useRect.object == 0
&& m_fontRectangles.size() + m_prioritizedLabels.size() >= Settings::maxLabels()
) {
if (isFastBail) {
return;
}
continue;
}
if (!o->drawLabel) {
continue;
}
const uint lineMargin = 3;
const QString &firstLine = isHovered? o->mapLabelHovered(): o->mapLabel();
// tightBoundingRect() might be slow on Windows according to docs
QRectF firstLineRect = fontMetrics.tightBoundingRect(firstLine);
float firstLineOffset = -firstLineRect.top();
firstLineRect.moveTop(0);
QRectF rect(firstLineRect); // complete boundingRect
rect.setHeight(rect.height() + lineMargin);
const auto &secondaryLines = isHovered? o->mapLabelSecondaryLinesHovered(): o->mapLabelSecondaryLines();
auto thisColor = isHovered || isHoveredSector
? Helpers::highLightColor(color)
: color;
auto thisSecondaryColor = isHovered || isHoveredSector
? Helpers::highLightColor(secondaryColor)
: secondaryColor;
QList<QRectF> secondaryRects;
float secondaryLinesOffset = 0.;
for (int iLine = 0; iLine < secondaryLines.size(); iLine++) {
auto _rect = fontMetricsSecondary.tightBoundingRect(secondaryLines[iLine]);
secondaryLinesOffset = -_rect.top();
_rect.moveTop(rect.bottom());
secondaryRects.insert(iLine, _rect);
// update complete boundingRect
rect.setHeight(rect.height() + _rect.height() + lineMargin);
rect.setWidth(qMax(rect.width(), _rect.width()));
}
// remove last lineMargin
rect.setHeight(rect.height() - lineMargin);
const uint distanceFromPos = 8;
int drawY = y - rect.height() - distanceFromPos;
int drawX = x - rect.width() / 2; // center horizontally
rect.moveTo(drawX, drawY);
bool isFriend = false;
// pilots, controllers
Client* cl = dynamic_cast <Client*> (o);
if (cl != 0) {
// Pilots and Controllers
isFriend = cl->isFriend();
} else {
// airports (having a controller that is in the friends list)
Airport* a = dynamic_cast <Airport*> (o);
if (a != 0) {
foreach (const auto c, a->allControllers()) {
if (c->isFriend()) {
// only if that is the primary airport
if (c->airports(false).contains(a)) {
isFriend = true;
break;
}
}
}
}
}
const QMarginsF backdropMargin(4, 5, 5, 5);
if (Settings::labelAlwaysBackdropped() || isHovered || isFriend) {
rect = rect.marginsAdded(backdropMargin);
}
if (useRect.object == 0) {
const QVector<QRectF> rects { // possible positions, with preferred ones first
// above
rect,
// right, below, left
rect.translated(rect.width() / 2 + distanceFromPos, rect.height() / 2 + distanceFromPos),
rect.translated(0, rect.height() + 2 * distanceFromPos),
rect.translated(-rect.width() / 2 - distanceFromPos, rect.height() / 2 + distanceFromPos),
// diagonal (for sectors)
rect.translated(rect.width() / 2 + distanceFromPos, 0),
rect.translated(rect.width() / 2 + distanceFromPos, rect.height() + 2 * distanceFromPos),
rect.translated(-rect.width() / 2 - distanceFromPos, rect.height() + 2 * distanceFromPos),
rect.translated(-rect.width() / 2 - distanceFromPos, 0),
// right, below, left (far, for sectors)
rect.translated(rect.width() + distanceFromPos, rect.height() / 2 + distanceFromPos),
rect.translated(0, rect.height() * 2 + 2 * distanceFromPos),
rect.translated(-rect.width() - distanceFromPos, rect.height() / 2 + distanceFromPos),
};
for (unsigned short i = 0; i <= tryNOtherPositions && i < rects.count(); i++) {
if (shouldDrawLabel(rects[i])) {
useRect.rect = rects[i];
useRect.object = o;
// we have not drawn that object before
break;
}
}
} else {
useRect.rect.setHeight(rect.height());
useRect.rect.setLeft(useRect.rect.left() + (useRect.rect.width() - rect.width()) / 2);
useRect.rect.setWidth(rect.width());
}
if (useRect.object == 0) {
continue;
}
if (Settings::labelAlwaysBackdropped() || isHovered || isFriend) {
// draw backdrop
QList<QPair<double, double> > rectPointsLatLon{ { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 } };
if (
local2latLon(
useRect.rect.left(), useRect.rect.top(),
rectPointsLatLon[0].first, rectPointsLatLon[0].second
)
&& local2latLon(
useRect.rect.right(), useRect.rect.top(),
rectPointsLatLon[1].first, rectPointsLatLon[1].second
)
&& local2latLon(
useRect.rect.right(), useRect.rect.bottom(),
rectPointsLatLon[2].first, rectPointsLatLon[2].second
)
&& local2latLon(
useRect.rect.left(), useRect.rect.bottom(),
rectPointsLatLon[3].first, rectPointsLatLon[3].second
)
) {
if (Settings::labelAlwaysBackdropped() || isHovered) {
auto bgColor = thisColor.lightnessF() < .5? Settings::labelHoveredBgColor(): Settings::labelHoveredBgDarkColor();
if (!isHovered) {
bgColor.setAlphaF(qMax(0., qMin(bgColor.alphaF(), (zoomTreshold - _zoom) / zoomTreshold * 1.5)));
}
qglColor(bgColor);
glBegin(GL_POLYGON);
foreach (const auto p, rectPointsLatLon) {
VERTEX(p.first, p.second);
}
glEnd();
// draw text shadow
if (isHovered) {
const auto shadowColor = Helpers::shadowColorForBg(bgColor);
qglColor(shadowColor);
renderText(
useRect.rect.left() + (useRect.rect.width() - firstLineRect.width()) / 2 + 1,
useRect.rect.top() + backdropMargin.top() + firstLineRect.top() + firstLineOffset + 1,
firstLine,
font
);
const auto shadowSecondaryColor = Helpers::shadowColorForBg(bgColor);
qglColor(shadowSecondaryColor);
for (int iLine = 0; iLine < secondaryLines.size(); iLine++) {
renderText(
useRect.rect.left() + (useRect.rect.width() - secondaryRects[iLine].width()) / 2 + 1,
useRect.rect.top() + backdropMargin.top() + secondaryRects[iLine].top() + secondaryLinesOffset + 1,
secondaryLines[iLine],
secondaryFont
);
}
}
}
if (isFriend) {
QColor friendsRectColor;
Airport* a = dynamic_cast <Airport*> (o);
if (a != 0) {
friendsRectColor = Settings::friendsAirportLabelRectColor();
} else {
Controller* c = dynamic_cast <Controller*> (o);
if (c != 0) {
friendsRectColor = Settings::friendsSectorLabelRectColor();
} else {
Pilot* c = dynamic_cast <Pilot*> (o);
if (c != 0) {
friendsRectColor = Settings::friendsPilotLabelRectColor();
} else {
Q_ASSERT(true);
}
}
}
if (!isHovered) {
friendsRectColor.setAlphaF(qMax(0., qMin(friendsRectColor.alphaF(), (zoomTreshold - _zoom) / zoomTreshold * 1.5)));
}
qglColor(friendsRectColor);
glLineWidth(.1);
glBegin(GL_LINE_LOOP);
foreach (const auto p, rectPointsLatLon) {
VERTEX(p.first, p.second);
}
glEnd();
}
}
}
qglColor(thisColor);
renderText(
useRect.rect.left() + (useRect.rect.width() - firstLineRect.width()) / 2,
useRect.rect.top() + backdropMargin.top() + firstLineRect.top() + firstLineOffset,
firstLine,
font
);
qglColor(thisSecondaryColor);
for (int iLine = 0; iLine < secondaryLines.size(); iLine++) {
renderText(
useRect.rect.left() + (useRect.rect.width() - secondaryRects[iLine].width()) / 2,
useRect.rect.top() + backdropMargin.top() + secondaryRects[iLine].top() + secondaryLinesOffset,
secondaryLines[iLine],
secondaryFont
);
}
m_fontRectangles.insert(useRect);
}
}
bool GLWidget::shouldDrawLabel(const QRectF &rect) {
foreach (const FontRectangle &fr, m_fontRectangles) {
if (rect.intersects(fr.rect)) {
return false;
}
}
return true;
}
QList<GLWidget::FontRectangle> GLWidget::fontRectanglesPrioritized() const {
auto priorityFor = [](const FontRectangle& fr) ->char {
if (qobject_cast<Airport*>(fr.object) != nullptr) {
return 30;
}
if (qobject_cast<Controller*>(fr.object) != nullptr) {
return 20;
}
if (qobject_cast<Pilot*>(fr.object) != nullptr) {
return 10;
}
return 0;
}
;
QMultiMap<char, GLWidget::FontRectangle> sorted;
foreach (const auto &fr, m_fontRectangles) {
sorted.insert(priorityFor(fr), fr);
}
return sorted.values();
}
void GLWidget::drawTestTextures() {
static QTimer* testTimer;
static float i = 0.;
if (testTimer == 0) {
testTimer = new QTimer(this);
connect(
testTimer, &QTimer::timeout, this, [&] {
i = fmod(i + .1, 30.); update();
}
);
testTimer->setInterval(30); testTimer->start();
}
glPushAttrib(GL_ENABLE_BIT);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, _earthTex); // with GL texture
for (float lat = 90. - i; lat >= -90.; lat -= 30.) {
for (float lon = -165.; lon < 180.; lon += 30.) {
drawBillboardWorldSize(lat, lon, QSizeF(.4, .4) * qCos(lat * Pi180));
}
}
const static QPixmap planePm(":/startup/logo"); // with QImage
bindTexture(planePm, GL_TEXTURE_2D, GL_RGBA, QGLContext::LinearFilteringBindOption); // that's cached by Qt
for (float lat = -90. + i; lat <= 90.; lat += 30.) {
for (float lon = -180.; lon < 180.; lon += 30.) {
drawBillboardScreenSize(lat, lon, planePm.size().scaled(64, 64, Qt::KeepAspectRatio));
}
}
glPopAttrib();
}
void GLWidget::drawBillboardScreenSize(GLfloat lat, GLfloat lon, const QSize &size) {
const GLfloat sizeFactor = .5 * _zoom / height();
drawBillboard(lat, lon, sizeFactor * size.width(), sizeFactor * size.height());
}
// size in world coordinates
void GLWidget::drawBillboardWorldSize(GLfloat lat, GLfloat lon, const QSizeF &size) {
drawBillboard(lat, lon, size.width() / 2., size.height() / 2.);
}
void GLWidget::drawBillboard(GLfloat lat, GLfloat lon, GLfloat halfWidth, GLfloat halfHeight, GLfloat alpha) {
glPushMatrix();
orthoMatrix(lat, lon);
glColor4f(1., 1., 1., alpha);
glBegin(GL_QUADS);
glTexCoord2i(0, 1);
glVertex2f(-halfWidth, halfHeight);
glTexCoord2i(1, 1);
glVertex2f(halfWidth, halfHeight);
glTexCoord2i(1, 0);
glVertex2f(halfWidth, -halfHeight);
glTexCoord2f(0, 0);
glVertex2f(-halfWidth, -halfHeight);
glEnd();
if (false) { // debug
drawCoordinateAxiiCurrentMatrix();
glColor3f(1., 1., 1.);
renderText(0, 0, 0, QString("%1/%2").arg(round(lat)).arg(round(lon)), QFont());
}
glPopMatrix();
}
void GLWidget::orthoMatrix(GLfloat lat, GLfloat lon) {
GLfloat theta = std::atan2(SY(lat, lon), SX(lat, lon));
GLfloat phi = std::asin(SZ(lat, lon));
glRotatef(90, 1, 0, 0);
glRotatef(theta / Pi180 + 90, 0, 1, 0);
glRotatef(-phi / Pi180, 1, 0, 0);
glTranslatef(0, 0, 1);
}
/////////////////////////
// Hover and map object actions
/////////////////////////
void GLWidget::configureHoverDebounce() {
m_hoverDebounceTimer->setSingleShot(true);
m_hoverDebounceTimer->setInterval(Settings::hoverDebounceMs());
}
void GLWidget::updateHoverState() {
// remove from fontRectangles when not hovered any more
foreach (const auto &o, m_hoveredObjects) {
if (!m_newHoveredObjects.contains(o)) {
foreach (const auto &fr, m_fontRectangles) {
if (fr.object == o) {
m_fontRectangles.remove(fr);
break;
}
}
}
}
m_hoveredObjects = m_newHoveredObjects;
invalidatePilots(); // for hovered objects' routes
update();
}
QList<MapObject*> GLWidget::objectsAt(int x, int y, double radiusSimple) const {
QList<MapObject*> result;
foreach (const auto &fr, fontRectanglesPrioritized()) { // scan text labels
if (fr.rect.adjusted(-10, -10, 10, 10).contains(x, y)) {
result.append(fr.object);
}
}
double lat, lon;
if (!local2latLon(x, y, lat, lon)) { // returns false if not on globe
return result;
}
double radiusDegQuad = Nm2Deg((qFuzzyIsNull(radiusSimple)? 30. * _zoom: radiusSimple));
radiusDegQuad *= radiusDegQuad;
foreach (Airport* a, NavData::instance()->airports.values()) {
if (a->active) {
double x = a->lat - lat;
double y = a->lon - lon;
if (x * x + y * y < radiusDegQuad) {
if (!result.contains(a)) {
result.append(a);
}
}
}
}
// this adds sectors and airports when hovered over/near them (disabled due to clutter)
// foreach(Controller* c, Whazzup::instance()->whazzupData().controllers.values()) {
// if(c->sector != 0 && c->sector->containsPoint(QPointF(lat, lon))) { // controllers with sectors
// result.insert(c);
// } else { // APP, TWR, GND, DEL
// int maxDist_nm = -1;
// if(c->isAppDep()) {
// maxDist_nm = Airport::symbologyAppRadius_nm;
// } else if(c->isTwr()) {
// maxDist_nm = Airport::symbologyTwrRadius_nm;
// } else if(c->isGnd()) {
// maxDist_nm = Airport::symbologyGndRadius_nm;
// } else if(c->isDel() || c->isAtis()) { // add ATIS to clientSelection
// maxDist_nm = Airport::symbologyDelRadius_nm;
// }
// foreach(auto* _a, c->airports()) {
// if(NavData::distance(_a->lat, _a->lon, lat, lon) < maxDist_nm) {
// result.insert(c);
// result.insert(_a);
// }
// }
// }
// }
foreach (Pilot* p, Whazzup::instance()->whazzupData().pilots.values()) {
double x = p->lat - lat;
double y = p->lon - lon;
if (x * x + y * y < radiusDegQuad) {
if (!result.contains(p)) {
result.append(p);
}
}
}
return result;
}
/////////////////////////
// draw-helper functions
/////////////////////////
void GLWidget::drawSelectionRectangle() {
QPoint current = mapFromGlobal(QCursor::pos());
double downLat, downLon;
if (local2latLon(_mouseDownPos.x(), _mouseDownPos.y(), downLat, downLon)) {
double currLat, currLon;
if (local2latLon(current.x(), current.y(), currLat, currLon)) {
// calculate a rectangle: approximating what the viewport will look after zoom
// (far from perfect but an okayish approximation...)
// down...: where the mouse was pressed down (1 edge of the rectangle)
// curr...: where it is now (the opposite edge)
double currLonDist = NavData::distance(currLat, downLon, currLat, currLon);
double downLonDist = NavData::distance(downLat, downLon, downLat, currLon);
double avgLonDist = (downLonDist + currLonDist) / 2.; // this needs to be the side length
DoublePair downLatCurrLon = NavData::greatCircleFraction(
downLat, downLon,
downLat, currLon,
avgLonDist / downLonDist
);
DoublePair currLatDownLon = NavData::greatCircleFraction(
currLat, currLon,
currLat, downLon,
avgLonDist / currLonDist
);
QList<QPair<double, double> > points;
points.append(DoublePair(downLat, downLon));
points.append(DoublePair(downLatCurrLon.first, downLatCurrLon.second));
points.append(DoublePair(currLat, currLon));
points.append(DoublePair(currLatDownLon.first, currLatDownLon.second));
points.append(DoublePair(downLat, downLon));
// draw background
glColor4f((GLfloat) 0., (GLfloat) 1., (GLfloat) 1., (GLfloat) .2);
glBegin(GL_POLYGON);
NavData::plotGreatCirclePoints(points);
glEnd();
// draw rectangle
glLineWidth(2.);
glColor4f((GLfloat) 0., (GLfloat) 1., (GLfloat) 1., (GLfloat) .5);
glBegin(GL_LINE_LOOP);
NavData::plotGreatCirclePoints(points);
glEnd();
// draw great circle course line
glLineWidth(2.);
glColor4f((GLfloat) 0., (GLfloat) 1., (GLfloat) 1., (GLfloat) .2);
glBegin(GL_LINE_STRIP);
NavData::plotGreatCirclePoints(QList<QPair<double, double> >() << points[0] << points[2]);
glEnd();
// information labels
const QFont font = Settings::firFont();
const QFontMetricsF fontMetrics(font, this);
// show position label
const QString currText = NavData::toEurocontrol(currLat, currLon);
int x, y;
if (latLon2local(currLat, currLon, &x, &y)) {
glColor4f((GLfloat) 0., (GLfloat) 0., (GLfloat) 0., (GLfloat) .7);
renderText(
x + 21,
y + 21,
currText, font
);
glColor4f((GLfloat) 0., (GLfloat) 1., (GLfloat) 1., (GLfloat) 1.);
renderText(
x + 20,
y + 20,
currText, font
);
}
// show distance label
const DoublePair middle = NavData::greatCircleFraction(downLat, downLon, currLat, currLon, .5);
const QString middleText = QString("%1 NM / TC %2 deg").arg(
NavData::distance(downLat, downLon, currLat, currLon),
0, 'f', 1
).arg(
NavData::courseTo(downLat, downLon, currLat, currLon),
3, 'f', 0, '0'
);
QRectF rect = fontMetrics.boundingRect(middleText);
if (latLon2local(middle.first, middle.second, &x, &y)) {
glColor4f((GLfloat) 0., (GLfloat) 0., (GLfloat) 0., (GLfloat) .7);
renderText(
x - rect.width() / 2. + 1,
y + rect.height() / 3. + 1,
middleText, font
);
glColor4f(0., 1., 1., 1.);
renderText(
x - rect.width() / 2.,
y + rect.height() / 3.,
middleText, font
);
}
}
}
}
/**
* for debugging. Shows axii at the Earth center. x = red, y = green, z = blue
*/
void GLWidget::drawCoordinateAxii() const {
glPushMatrix();
glLoadIdentity();
glTranslatef(0, 0, -9);
glRotated(_xRot, 1, 0, 0);
glRotated(_yRot, 0, 1, 0);
glRotated(_zRot, 0, 0, 1);
drawCoordinateAxiiCurrentMatrix();
glPopMatrix();
}
/**
* for debugging. Draws the axii. x = red, y = green, z = blue
*/
void GLWidget::drawCoordinateAxiiCurrentMatrix() const {
GLUquadricObj* q = gluNewQuadric();
gluQuadricNormals(q, GLU_SMOOTH);
glPushMatrix();
glPushAttrib(GL_ENABLE_BIT | GL_DEPTH_BUFFER_BIT | GL_CURRENT_BIT);
glDisable(GL_TEXTURE_2D);
glColor3f(0, 0, 0); gluSphere(q, 0.02, 64, 32); // center
glRotatef(90, 0, 1, 0);
glColor3f(1, 0, 0); gluCylinder(q, 0.02, 0.0, 0.3, 64, 1); // x-axis
glRotatef(90, 0, -1, 0);
glRotatef(90, -1, 0, 0);
glColor3f(0, 1, 0); gluCylinder(q, 0.02, 0.0, 0.3, 64, 1); // y-axis
glRotatef(90, 1, 0, 0);
glColor3f(0, 0, 1); gluCylinder(q, 0.02, 0.0, 0.3, 64, 1); // z-axis
glPopAttrib();
glPopMatrix();
}
/////////////////////////
// uncategorized
/////////////////////////
void GLWidget::newWhazzupData(bool isNew) {
qDebug() << "isNew =" << isNew;
if (isNew) {
// update airports
NavData::instance()->updateData(Whazzup::instance()->whazzupData());
m_hoveredObjects.clear();
m_fontRectangles.clear();
invalidatePilots();
invalidateControllers();
invalidateAirports();
m_friendPositions = Whazzup::instance()->whazzupData().friendsLatLon();
}
qDebug() << "-- finished";
}
void GLWidget::configureUpdateTimer() {
const bool isRunFullFps = Settings::highlightFriends() && Settings::animateFriendsHighlight();
if (isRunFullFps) {
m_updateTimer->setInterval(40);
if (!m_updateTimer->isActive()) {
m_updateTimer->start();
}
} else {
m_updateTimer->stop();
update();
}
}
//////////////////////////////////
// Clouds, Lightning and Earth Textures
//////////////////////////////////
void GLWidget::parseTexture() {
qDebug();
GuiMessages::progress("textures", "Preparing textures...");
QImage earthTexIm;
if (Settings::glTextures()) {
QString earthTexFile = Settings::dataDirectory(QString("textures/%1").arg(Settings::glTextureEarth()));
qDebug() << "loading earth texture";
GuiMessages::progress("textures", "Preparing textures: loading earth...");
earthTexIm.load(earthTexFile);
}
if (earthTexIm.isNull()) {
qWarning() << "Unable to load texture file: "
<< Settings::dataDirectory(QString("textures/%1").arg(Settings::glTextureEarth()));
} else {
GLint max_texture_size; glGetIntegerv(GL_MAX_TEXTURE_SIZE, &max_texture_size);
qDebug() << "OpenGL reported MAX_TEXTURE_SIZE as" << max_texture_size;
// multitexturing units, if we need it once (headers in GL/glext.h, on Windows not available ?!)
//GLint max_texture_units; glGetIntegerv(GL_MAX_TEXTURE_UNITS, &max_texture_units);
//qDebug() << "OpenGL reported MAX_TEXTURE_UNITS as" << max_texture_units;
qDebug() << "Binding parsed texture as" << earthTexIm.width()
<< "x" << earthTexIm.height() << "px texture";
qDebug() << "Generating texture coordinates";
GuiMessages::progress("textures", "Preparing textures: preparing texture coordinates...");
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// glGenTextures(1, &earthTex); // bindTexture does this the Qt'ish way already
qDebug() << "Emptying error buffer";
glGetError(); // empty the error buffer
qDebug() << "Binding texture";
_earthTex = bindTexture(
earthTexIm,
GL_TEXTURE_2D,
GL_RGBA,
QGLContext::LinearFilteringBindOption
); // QGLContext::MipmapBindOption
if (GLenum glError = glGetError()) {
qCritical() << QString("OpenGL returned an error (0x%1)")
.arg((int) glError, 4, 16, QChar('0'));
}
}
qDebug() << "-- finished";
update();
GuiMessages::remove("textures");
}
void GLWidget::createLights() {
//const GLfloat earthAmbient[] = {0, 0, 0, 1};
const GLfloat earthDiffuse[] = { 1, 1, 1, 1 };
const GLfloat earthSpecular[] = {
(GLfloat) Settings::specularColor().redF(),
(GLfloat) Settings::specularColor().greenF(),
(GLfloat) Settings::specularColor().blueF(),
(GLfloat) Settings::specularColor().alphaF()
};
const GLfloat earthEmission[] = { 0, 0, 0, 1 };
const GLfloat earthShininess[] = { (GLfloat) Settings::earthShininess() };
//glMaterialfv(GL_FRONT, GL_AMBIENT, earthAmbient); // GL_AMBIENT, GL_DIFFUSE, GL_SPECULAR,
glMaterialfv(GL_FRONT, GL_DIFFUSE, earthDiffuse); // ...GL_EMISSION, GL_SHININESS, GL_AMBIENT_AND_DIFFUSE,
glMaterialfv(GL_FRONT, GL_SPECULAR, earthSpecular); // ...GL_COLOR_INDEXES
glMaterialfv(GL_FRONT, GL_EMISSION, earthEmission); //
glMaterialfv(GL_FRONT, GL_SHININESS, earthShininess); //... only DIFFUSE has an own alpha channel!
glColorMaterial(GL_FRONT, GL_AMBIENT); // GL_EMISSION, GL_AMBIENT, GL_DIFFUSE, GL_SPECULAR,
// GL_AMBIENT_AND_DIFFUSE
glEnable(GL_COLOR_MATERIAL); // controls if glColor will drive the given values in glColorMaterial
const GLfloat sunAmbient[] = { 0., 0., 0., 1. };
QColor adjustSunDiffuse = Settings::sunLightColor();
if (Settings::glLights() > 1) {
adjustSunDiffuse = adjustSunDiffuse.darker(
100. * (Settings::glLights() - // reduce light intensity by number of
// lights...
Settings::glLightsSpread() / 180. * (Settings::glLights() - 1))
); // ...and
// increase
// again
// by
// their
// distribution
}
const GLfloat sunDiffuse[] = {
(GLfloat) adjustSunDiffuse.redF(),
(GLfloat) adjustSunDiffuse.greenF(),
(GLfloat) adjustSunDiffuse.blueF(),
(GLfloat) adjustSunDiffuse.alphaF()
};
//const GLfloat sunSpecular[] = {1, 1, 1, 1}; // we drive this via material values
for (int light = 0; light < 8; light++) {
if (light < Settings::glLights()) {
glLightfv(GL_LIGHT0 + light, GL_AMBIENT, sunAmbient); // GL_AMBIENT, GL_DIFFUSE, GL_SPECULAR,
// GL_POSITION,
// GL_SPOT_CUTOFF,
glLightfv(GL_LIGHT0 + light, GL_DIFFUSE, sunDiffuse); // ...GL_SPOT_DIRECTION, GL_SPOT_EXPONENT,
// GL_CONSTANT_ATTENUATION,
//glLightfv(GL_LIGHT0 + light, GL_SPECULAR, sunSpecular);// ...GL_LINEAR_ATTENUATION
// GL_QUADRATIC_ATTENUATION
glEnable(GL_LIGHT0 + light);
} else {
glDisable(GL_LIGHT0 + light);
}
}
const GLfloat modelAmbient[] = { (GLfloat) .2, (GLfloat) .2, (GLfloat) .2, (GLfloat) 1. }; // the "background"
// ambient light
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, modelAmbient); // GL_LIGHT_MODEL_AMBIENT, GL_LIGHT_MODEL_COLOR_CONTROL,
//glLightModelf(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE); // ...GL_LIGHT_MODEL_LOCAL_VIEWER,
// GL_LIGHT_MODEL_TWO_SIDE
glShadeModel(GL_SMOOTH); // SMOOTH or FLAT
glEnable(GL_NORMALIZE);
_lightsGenerated = true;
}
| 103,893
|
C++
|
.cpp
| 2,458
| 31.633442
| 166
| 0.562866
|
qutescoop/qutescoop
| 33
| 15
| 21
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,636
|
Airport.cpp
|
qutescoop_qutescoop/src/Airport.cpp
|
#include "Airport.h"
#include "helpers.h"
#include "NavData.h"
#include "Settings.h"
#include "dialogs/AirportDetails.h"
#include "src/mustache/Renderer.h"
const QRegularExpression Airport::pdcRegExp = QRegularExpression(
"PDC.{0,20}\\W([A-Z]{4})(\\W|$)", QRegularExpression::MultilineOption | QRegularExpression::InvertedGreedinessOption
);
Airport::Airport(const QStringList& list, unsigned int debugLineNumber)
: MapObject(),
_appDisplayList(0), _twrDisplayList(0), _gndDisplayList(0), _delDisplayList(0) {
resetWhazzupStatus();
if (list.size() != 6) {
QMessageLogger("airports.dat", debugLineNumber, QT_MESSAGELOG_FUNC).critical()
<< "While processing line" << list.join(':') << ": Found" << list.size() << "fields, expected exactly 6.";
exit(EXIT_FAILURE);
}
id = list[0];
name = list[1];
city = list[2];
countryCode = list[3];
if (countryCode != "" && NavData::instance()->countryCodes.value(countryCode, "") == "") {
QMessageLogger("airports.dat", debugLineNumber, QT_MESSAGELOG_FUNC).critical()
<< "While processing line" << list.join(':') << ": Could not find country" << countryCode;
exit(EXIT_FAILURE);
}
lat = list[4].toDouble();
lon = list[5].toDouble();
}
Airport::~Airport() {
MustacheQs::Renderer::teardownContext(this);
if (_appDisplayList != 0 && glIsList(_appDisplayList) == GL_TRUE) {
glDeleteLists(_appDisplayList, 1);
}
if (_twrDisplayList != 0 && glIsList(_twrDisplayList) == GL_TRUE) {
glDeleteLists(_twrDisplayList, 1);
}
if (_gndDisplayList != 0 && glIsList(_gndDisplayList) == GL_TRUE) {
glDeleteLists(_gndDisplayList, 1);
}
if (_delDisplayList != 0 && glIsList(_delDisplayList) == GL_TRUE) {
glDeleteLists(_delDisplayList, 1);
}
}
void Airport::resetWhazzupStatus() {
active = false;
dels.clear();
atiss.clear();
gnds.clear();
twrs.clear();
appDeps.clear();
arrivals.clear();
departures.clear();
nMaybeFilteredArrivals = 0;
nMaybeFilteredDepartures = 0;
}
void Airport::addArrival(Pilot* client) {
arrivals.insert(client);
active = true;
}
void Airport::addDeparture(Pilot* client) {
departures.insert(client);
active = true;
}
uint Airport::congestion() const {
return nMaybeFilteredArrivals + nMaybeFilteredDepartures;
}
void Airport::addController(Controller* c) {
if (c->isAppDep()) {
appDeps.insert(c);
}
if (c->isTwr()) {
twrs.insert(c);
}
if (c->isGnd()) {
gnds.insert(c);
}
if (c->isDel()) {
dels.insert(c);
}
if (c->isAtis()) {
atiss.insert(c);
}
active = true;
}
const GLuint& Airport::appDisplayList() {
if (_appDisplayList != 0 && glIsList(_appDisplayList) == GL_TRUE) {
return _appDisplayList;
}
_appDisplayList = glGenLists(1);
glNewList(_appDisplayList, GL_COMPILE);
appGl(
Settings::appCenterColor(),
Settings::appMarginColor(),
Settings::appBorderLineColor(),
Settings::appBorderLineWidth()
);
glEndList();
return _appDisplayList;
}
void Airport::appGl(const QColor &middleColor, const QColor &marginColor, const QColor &borderColor, const GLfloat &borderLineWidth) const {
auto otherAirportsOfAppControllers = QSet<Airport*>();
foreach (const auto* approach, appDeps) {
foreach (const auto& airport, approach->airports()) {
if (airport != this) {
otherAirportsOfAppControllers.insert(airport);
}
}
}
glBegin(GL_TRIANGLE_FAN);
glColor4f(middleColor.redF(), middleColor.greenF(), middleColor.blueF(), middleColor.alphaF());
VERTEX(lat, lon);
for (short int i = 0; i <= 360; i += 10) {
auto _p = NavData::pointDistanceBearing(lat, lon, Airport::symbologyAppRadius_nm, i);
short int airportsClose = 0;
foreach (const auto* a, otherAirportsOfAppControllers) {
auto _dist = NavData::distance(_p.first, _p.second, a->lat, a->lon);
airportsClose += _dist < Airport::symbologyAppRadius_nm;
}
if (airportsClose > 0) {
// reduce opacity in overlap areas - https://github.com/qutescoop/qutescoop/issues/211
// (this is still a TRIANGLE_FAN, so it has the potential to be a bit meh...)
glColor4f(marginColor.redF(), marginColor.greenF(), marginColor.blueF(), marginColor.alphaF() / (airportsClose + 1));
} else {
glColor4f(marginColor.redF(), marginColor.greenF(), marginColor.blueF(), marginColor.alphaF());
}
VERTEX(_p.first, _p.second);
}
glEnd();
if (borderLineWidth > 0.) {
glLineWidth(borderLineWidth);
glBegin(GL_LINE_STRIP);
glColor4f(borderColor.redF(), borderColor.greenF(), borderColor.blueF(), borderColor.alphaF());
for (short int i = 0; i <= 360; i += 1) {
auto _p = NavData::pointDistanceBearing(lat, lon, Airport::symbologyAppRadius_nm, i);
auto isAirportsClose = false;
foreach (const auto* a, otherAirportsOfAppControllers) {
auto _dist = NavData::distance(_p.first, _p.second, a->lat, a->lon);
if (_dist < Airport::symbologyAppRadius_nm) {
isAirportsClose = true;
}
}
if (isAirportsClose) {
// hide border line on overlap - https://github.com/qutescoop/qutescoop/issues/211
glColor4f(borderColor.redF(), borderColor.greenF(), borderColor.blueF(), 0.);
} else {
glColor4f(borderColor.redF(), borderColor.greenF(), borderColor.blueF(), borderColor.alphaF());
}
VERTEX(_p.first, _p.second);
}
glEnd();
}
}
const GLuint& Airport::twrDisplayList() {
if (_twrDisplayList != 0 && glIsList(_twrDisplayList) == GL_TRUE) {
return _twrDisplayList;
}
_twrDisplayList = glGenLists(1);
glNewList(_twrDisplayList, GL_COMPILE);
twrGl(
Settings::twrCenterColor(),
Settings::twrMarginColor(),
Settings::twrBorderLineColor(),
Settings::twrBorderLineWidth()
);
glEndList();
return _twrDisplayList;
}
void Airport::twrGl(const QColor &middleColor, const QColor &marginColor, const QColor &borderColor, const GLfloat &borderLineWidth) const {
glBegin(GL_TRIANGLE_FAN);
glColor4f(middleColor.redF(), middleColor.greenF(), middleColor.blueF(), middleColor.alphaF());
VERTEX(lat, lon);
glColor4f(marginColor.redF(), marginColor.greenF(), marginColor.blueF(), marginColor.alphaF());
for (int i = 0; i <= 360; i += 10) {
auto _p = NavData::pointDistanceBearing(lat, lon, Airport::symbologyTwrRadius_nm, i);
VERTEX(_p.first, _p.second);
}
glEnd();
if (borderLineWidth > 0.) {
glLineWidth(borderLineWidth);
glBegin(GL_LINE_LOOP);
glColor4f(borderColor.redF(), borderColor.greenF(), borderColor.blueF(), borderColor.alphaF());
for (int i = 0; i <= 360; i += 10) {
auto _p = NavData::pointDistanceBearing(lat, lon, Airport::symbologyTwrRadius_nm, i);
VERTEX(_p.first, _p.second);
}
glEnd();
}
}
const QString Airport::trafficString() const {
auto tmpl = "{#allArrs}{allArrs}{/allArrs}{^allArrs}-{/allArrs}/{#allDeps}{allDeps}{/allDeps}{^allDeps}-{/allDeps}";
if (Settings::filterTraffic()) {
tmpl = "{#arrs}{arrs}{/arrs}{^arrs}-{/arrs}/{#deps}{deps}{/deps}{^deps}-{/deps}";
}
return MustacheQs::Renderer::render(tmpl, (QObject*) this);
}
const QString Airport::controllersString() const {
QStringList controllers;
if (!dels.empty()) {
controllers << "D";
}
if (!gnds.empty()) {
controllers << "G";
}
if (!twrs.empty()) {
controllers << "T";
}
if (!appDeps.empty()) {
controllers << "A";
}
return controllers.join(",");
}
const QString Airport::atisCodeString() const {
QStringList ret;
foreach (const auto atis, atiss) {
const QString code = atis->atisCode.isEmpty()? "?": atis->atisCode;
QString suffix;
const auto atcLabelTokens = atis->atcLabelTokens();
if (atcLabelTokens.size() > 2) {
suffix = atcLabelTokens[1];
}
ret << (suffix.isEmpty()
? ": " + code
: "_" + suffix + ": " + code);
}
if (ret.isEmpty()) {
return "";
}
return "ATIS" + ret.join(", ");
}
const QString Airport::frequencyString() const {
QStringList ret;
QStringList controllers;
foreach (const auto c, atiss) {
const auto atcLabelTokens = c->atcLabelTokens();
const QString atisCode = c->atisCode.isEmpty()? "": ": " + c->atisCode;
QString suffix;
if (atiss.size() > 1 && atcLabelTokens.size() > 2) {
suffix = atcLabelTokens[1];
}
controllers << ((c->frequency.length() > 1? c->frequency: "") + (suffix.isEmpty()? "": "_" + suffix) + atisCode);
}
if (!controllers.empty()) {
ret << "ATIS: " + controllers.join(", ");
}
const QList<QPair < QString, QSet<Controller*> > > controllerSections = {
{ "DEL", dels },
{ "GND", gnds },
{ "TWR", twrs },
{ "APP", appDeps },
};
for (auto i = controllerSections.constBegin(); i != controllerSections.constEnd(); ++i) {
QStringList controllers;
QSet<QString> frequencies;
foreach (const auto c, i->second) {
const auto atcLabelTokens = c->atcLabelTokens();
QString suffix;
if (i->second.size() > 1 && atcLabelTokens.size() > 2) {
suffix = atcLabelTokens[1];
}
if (frequencies.contains(c->frequency)) {
continue;
}
controllers << ((c->frequency.length() > 1? c->frequency: "") + (suffix.isEmpty()? "": "_" + suffix));
frequencies.insert(c->frequency);
}
if (!controllers.empty()) {
ret << i->first + (controllers.join("").isEmpty()? "": ": " + controllers.join(", "));
}
}
return ret.join("\n");
}
const QString Airport::pdcString(const QString &prepend, bool alwaysWithIdentifier) const {
QStringList matches;
foreach (const auto* c, allControllers()) {
auto match = pdcRegExp.match(c->atisMessage);
if (match.hasMatch()) {
auto logon = match.captured(1);
if (id == logon) {
if (!alwaysWithIdentifier) {
// found perfect match
return prepend;
}
}
if (!matches.contains(logon)) {
matches << logon;
}
}
}
return matches.isEmpty()? "": prepend + matches.join(",");
}
const GLuint& Airport::gndDisplayList() {
if (_gndDisplayList != 0 && glIsList(_gndDisplayList) == GL_TRUE) {
return _gndDisplayList;
}
QColor fillColor = Settings::gndFillColor();
QColor borderColor = Settings::gndBorderLineColor();
GLfloat borderLineWidth = Settings::gndBorderLineWidth();
_gndDisplayList = glGenLists(1);
glNewList(_gndDisplayList, GL_COMPILE);
GLfloat circle_distort = qCos(lat * Pi180);
GLfloat innerDeltaLon = (GLfloat) Nm2Deg(Airport::symbologyGndRadius_nm / 2.);
GLfloat outerDeltaLon = (GLfloat) Nm2Deg(Airport::symbologyGndRadius_nm / .7);
GLfloat innerDeltaLat = circle_distort * innerDeltaLon;
GLfloat outerDeltaLat = circle_distort * outerDeltaLon;
// draw a star shape
const QList<QPointF> points{
{ lat + outerDeltaLat, lon },
{ lat + innerDeltaLat, lon + innerDeltaLon },
{ lat, lon + outerDeltaLon },
{ lat - innerDeltaLat, lon + innerDeltaLon },
{ lat - outerDeltaLat, lon },
{ lat - innerDeltaLat, lon - innerDeltaLon },
{ lat, lon - outerDeltaLon },
{ lat + innerDeltaLat, lon - innerDeltaLon },
{ lat + outerDeltaLat, lon },
};
glColor4f(fillColor.redF(), fillColor.greenF(), fillColor.blueF(), fillColor.alphaF());
glBegin(GL_TRIANGLE_FAN);
VERTEX(lat, lon);
for (int i = 0; i < points.size(); i++) {
VERTEX(points[i].x(), points[i].y());
}
glEnd();
if (borderLineWidth > 0.) {
glLineWidth(borderLineWidth);
glBegin(GL_LINE_LOOP);
glColor4f(borderColor.redF(), borderColor.greenF(), borderColor.blueF(), borderColor.alphaF());
for (int i = 0; i < points.size(); i++) {
VERTEX(points[i].x(), points[i].y());
}
glEnd();
}
glEndList();
return _gndDisplayList;
}
const GLuint& Airport::delDisplayList() {
if (_delDisplayList != 0 && glIsList(_delDisplayList) == GL_TRUE) {
return _delDisplayList;
}
QColor fillColor = Settings::delFillColor();
QColor borderColor = Settings::delBorderLineColor();
GLfloat borderLineWidth = Settings::delBorderLineWidth();
_delDisplayList = glGenLists(1);
glNewList(_delDisplayList, GL_COMPILE);
GLfloat circle_distort = qCos(lat * Pi180);
GLfloat deltaLon = (GLfloat) Nm2Deg(Airport::symbologyDelRadius_nm / .7);
GLfloat deltaLat = circle_distort * deltaLon;
QList<QPointF> points;
for (int i = 0; i <= 360; i += 10) {
points.append(
QPointF(
lon + deltaLon * qSin(i * Pi180),
lat + deltaLat * qCos(i * Pi180)
)
);
}
glColor4f(fillColor.redF(), fillColor.greenF(), fillColor.blueF(), fillColor.alphaF());
glBegin(GL_TRIANGLE_FAN);
VERTEX(lat, lon);
for (int i = 0; i < points.size(); i++) {
VERTEX(points[i].y(), points[i].x());
}
glEnd();
if (borderLineWidth > 0.) {
glLineWidth(borderLineWidth);
glBegin(GL_LINE_LOOP);
glColor4f(borderColor.redF(), borderColor.greenF(), borderColor.blueF(), borderColor.alphaF());
for (int i = 0; i < points.size(); i++) {
VERTEX(points[i].y(), points[i].x());
}
glEnd();
}
glEndList();
return _delDisplayList;
}
void Airport::showDetailsDialog() {
AirportDetails* infoDialog = AirportDetails::instance();
infoDialog->refresh(this);
infoDialog->show();
infoDialog->raise();
infoDialog->activateWindow();
infoDialog->setFocus();
}
QSet<Controller*> Airport::allControllers() const {
return appDeps + twrs + gnds + dels + atiss;
}
bool Airport::matches(const QRegExp& regex) const {
return id.contains(regex)
|| name.contains(regex)
|| city.contains(regex)
|| countryCode.contains(regex)
|| MapObject::matches(regex);
}
const QString Airport::prettyName() const {
if (name.contains(city)) {
return name;
}
foreach (const auto part, city.split(QRegExp("\\W"), Qt::SkipEmptyParts)) {
if (name.contains(part)) {
return name;
}
}
return name + (city.isEmpty()? "": ", " + city);
}
QString Airport::mapLabel() const {
auto tmpl = Settings::airportPrimaryContent();
return MustacheQs::Renderer::render(tmpl, (QObject*) this);
}
QString Airport::mapLabelHovered() const {
auto tmpl = Settings::airportPrimaryContentHovered();
return MustacheQs::Renderer::render(tmpl, (QObject*) this);
}
QStringList Airport::mapLabelSecondaryLines() const {
auto tmpl = Settings::airportSecondaryContent();
return Helpers::linesFilteredTrimmed(
MustacheQs::Renderer::render(tmpl, (QObject*) this)
);
}
QStringList Airport::mapLabelSecondaryLinesHovered() const {
auto tmpl = Settings::airportSecondaryContentHovered();
return Helpers::linesFilteredTrimmed(
MustacheQs::Renderer::render(tmpl, (QObject*) this)
);
}
QString Airport::livestreamString() const {
QStringList ret;
foreach (const auto c, allControllers()) {
const auto str = c->livestreamString();
if (!str.isEmpty()) {
ret << str;
}
}
return ret.join(" ");
}
const QString Airport::shortLabel() const {
auto _trafficString = trafficString();
return QString("%1%2").arg(
id,
_trafficString.isEmpty()? "": " " + trafficString()
);
}
QString Airport::toolTip() const {
return QString("%1 (%2, %3)").arg(
id,
prettyName(),
countryCode
);
}
bool Airport::hasPrimaryAction() const {
return true;
}
void Airport::primaryAction() {
showDetailsDialog();
}
| 16,687
|
C++
|
.cpp
| 456
| 29.660088
| 140
| 0.611878
|
qutescoop/qutescoop
| 33
| 15
| 21
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,637
|
NavData.cpp
|
qutescoop_qutescoop/src/NavData.cpp
|
#include "NavData.h"
#include "Airport.h"
#include "FileReader.h"
#include "helpers.h"
#include "SectorReader.h"
#include "Settings.h"
#include <QRegExp>
NavData* navDataInstance = 0;
NavData* NavData::instance(bool createIfNoInstance) {
if (navDataInstance == 0 && createIfNoInstance) {
navDataInstance = new NavData();
}
return navDataInstance;
}
NavData::NavData() {}
NavData::~NavData() {
foreach (const Airport* a, airports) {
delete a;
}
foreach (const Sector* s, sectors) {
delete s;
}
}
void NavData::load() {
loadCountryCodes(Settings::dataDirectory("data/countrycodes.dat"));
loadAirports(Settings::dataDirectory("data/airports.dat"));
loadControllerAirportsMapping(Settings::dataDirectory("data/controllerAirportsMapping.dat"));
loadSectors();
loadAirlineCodes(Settings::dataDirectory("data/airlines.dat"));
emit loaded();
}
void NavData::loadAirports(const QString& filename) {
airports.clear();
activeAirports.clear();
FileReader fr(filename);
auto countMissingCountry = 0;
auto count = 0;
while (!fr.atEnd()) {
++count;
QString _line = fr.nextLine().trimmed();
if (_line.isEmpty() || _line.startsWith(";")) {
continue;
}
Airport* airport = new Airport(_line.split(':'), count);
if (airport->countryCode == 0) {
++countMissingCountry;
}
if (airport == 0 && airport->id.isEmpty()) {
continue;
}
airports.insert(airport->id, airport);
}
if (countMissingCountry != 0) {
qWarning() << countMissingCountry << "airports are missing a country code. Please help by adding them in data/airports.dat.";
}
}
void NavData::loadControllerAirportsMapping(const QString &filePath) {
m_controllerAirportsMapping.clear();
FileReader fr(filePath);
unsigned int count = 0;
while (!fr.atEnd()) {
++count;
QString _line = fr.nextLine().trimmed();
if (_line.isEmpty() || _line.startsWith(";")) {
continue;
}
QStringList _fields = _line.split(':');
if (_fields.size() != 3) {
QMessageLogger(filePath.toLocal8Bit(), count, QT_MESSAGELOG_FUNC).critical()
<< _line << ": Expected 3 fields";
exit(EXIT_FAILURE);
}
ControllerAirportsMapping _cam;
_cam.prefix = _fields[0];
_cam.suffixes = _fields[1].split(" ", Qt::SkipEmptyParts);
foreach (const auto _airportIcao, _fields[2].split(" ", Qt::SkipEmptyParts)) {
if (airports.contains(_airportIcao)) {
_cam.airports.insert(airports.value(_airportIcao));
} else {
QMessageLogger(filePath.toLocal8Bit(), count, QT_MESSAGELOG_FUNC).critical()
<< _line << ": Airport" << _airportIcao << "not found in airports.dat";
exit(EXIT_FAILURE);
}
}
m_controllerAirportsMapping.append(_cam);
}
}
void NavData::loadCountryCodes(const QString& filePath) {
countryCodes.clear();
FileReader fr(filePath);
unsigned int count = 0;
while (!fr.atEnd()) {
++count;
QString _line = fr.nextLine().trimmed();
if (_line.isEmpty() || _line.startsWith(";")) {
continue;
}
QStringList _fields = _line.split(':');
if (_fields.size() != 2) {
QMessageLogger(filePath.toLocal8Bit(), count, QT_MESSAGELOG_FUNC).critical()
<< _line << ": Expected 2 fields";
exit(EXIT_FAILURE);
}
countryCodes[_fields.first()] = _fields.last();
}
}
void NavData::loadSectors() {
SectorReader().loadSectors(sectors);
}
void NavData::loadAirlineCodes(const QString &filePath) {
qDebug() << "loading airlines from" << filePath;
foreach (const auto _a, airlines) {
delete _a;
}
airlines.clear();
auto count = 0;
FileReader fr(filePath);
while (!fr.atEnd()) {
QString _line = fr.nextLine();
if (_line.isEmpty() || _line.startsWith(";")) {
continue;
}
QStringList _fields = _line.split(0x09); // 0x09 code for Tabulator
if (_fields.count() != 4) {
QMessageLogger(filePath.toLocal8Bit(), count, QT_MESSAGELOG_FUNC).critical()
<< _line << ": Expected 4 fields";
exit(EXIT_FAILURE);
}
auto airline = new Airline(_fields[0], _fields[1], _fields[2], _fields[3]);
airlines[airline->code] = airline;
count++;
}
qDebug() << "loaded" << count << "airlines";
}
double NavData::distance(double lat1, double lon1, double lat2, double lon2) {
lat1 *= Pi180;
lon1 *= Pi180;
lat2 *= Pi180;
lon2 *= Pi180;
double result = qAcos(qSin(lat1) * qSin(lat2) + qCos(lat1) * qCos(lat2) * qCos(lon1 - lon2));
if (qIsNaN(result)) {
return 0;
}
return result * 60.0 / Pi180;
}
QPair<double, double> NavData::pointDistanceBearing(double lat, double lon, double dist, double heading) {
lat *= Pi180;
lon *= Pi180;
heading = (360 - heading) * Pi180;
dist = dist / 60.0 * Pi180;
double rlat = qAsin(qSin(lat) * qCos(dist) + qCos(lat) * qSin(dist) * qCos(heading));
double dlon = qAtan2(qSin(heading) * qSin(dist) * qCos(lat), qCos(dist) - qSin(lat) * qSin(lat));
double rlon = fmod(lon - dlon + M_PI, 2 * M_PI) - M_PI;
return QPair<double, double> (rlat / Pi180, rlon / Pi180);
}
Airport* NavData::airportAt(double lat, double lon, double maxDist) const {
foreach (Airport* a, airports.values()) {
if (distance(a->lat, a->lon, lat, lon) <= maxDist) {
return a;
}
}
return 0;
}
QSet<Airport*> NavData::additionalMatchedAirportsForController(QString prefix, QString suffix) const {
QSet<Airport*> ret;
foreach (const auto _cam, m_controllerAirportsMapping) {
if (
_cam.prefix == prefix
&& (_cam.suffixes.isEmpty() || _cam.suffixes.contains(suffix))
) {
foreach (const auto _a, _cam.airports) {
ret.insert(_a);
}
}
}
return ret;
}
void NavData::updateData(const WhazzupData& whazzupData) {
qDebug() << "on" << airports.size() << "airports";
foreach (Airport* a, activeAirports.values()) {
a->resetWhazzupStatus();
}
QSet<Airport*> newActiveAirportsSet;
QList<Pilot*> allpilots = whazzupData.allPilots();
for (int i = 0; i < allpilots.size(); i++) {
Pilot* p = allpilots[i];
if (p == 0) {
continue;
}
Airport* dep = p->depAirport();
if (dep != 0) {
dep->addDeparture(p);
newActiveAirportsSet.insert(dep);
if (
!Settings::filterTraffic()
|| (p->distanceFromDeparture() < Settings::filterDistance())
) {
dep->nMaybeFilteredDepartures++;
}
} else if (p->flightStatus() == Pilot::BUSH) { // no flightplan yet?
Airport* a = airportAt(p->lat, p->lon, 3.);
if (a != 0) {
a->addDeparture(p);
a->nMaybeFilteredDepartures++;
newActiveAirportsSet.insert(a);
}
}
Airport* dest = p->destAirport();
if (dest != 0) {
dest->addArrival(p);
newActiveAirportsSet.insert(dest);
if (
(
!Settings::filterTraffic()
|| (
(p->distanceToDestination() < Settings::filterDistance())
|| (p->eet().hour() + p->eet().minute() / 60. < Settings::filterArriving())
)
)
&& (p->flightStatus() != Pilot::FlightStatus::BLOCKED && p->flightStatus() != Pilot::FlightStatus::GROUND_ARR)
) {
dest->nMaybeFilteredArrivals++;
}
}
}
foreach (Controller* c, whazzupData.controllers) {
foreach (const auto _airport, c->airports()) {
_airport->addController(c);
newActiveAirportsSet.insert(_airport);
}
}
activeAirports.clear();
foreach (Airport* a, newActiveAirportsSet) {
activeAirports.insert(a->congestion(), a);
}
qDebug() << "-- finished";
}
void NavData::accept(SearchVisitor* visitor) {
foreach (Airport* a, airports) {
visitor->visit(a);
}
visitor->airlines = airlines;
}
double NavData::courseTo(double lat1, double lon1, double lat2, double lon2) {
lat1 *= Pi180;
lon1 *= Pi180;
lat2 *= Pi180;
lon2 *= Pi180;
double d = qAcos(qSin(lat1) * qSin(lat2) + qCos(lat1) * qCos(lat2) * qCos(lon1 - lon2));
double tc1;
if (qSin(lon2 - lon1) < 0.) {
tc1 = qAcos((qSin(lat2) - qSin(lat1) * qCos(d)) / (qSin(d) * qCos(lat1)));
} else {
tc1 = 2 * M_PI - qAcos((qSin(lat2) - qSin(lat1) * qCos(d)) / (qSin(d) * qCos(lat1)));
}
return 360. - (tc1 / Pi180);
}
QPair<double, double> NavData::greatCircleFraction(
double lat1,
double lon1,
double lat2,
double lon2,
double f
) {
if (qFuzzyCompare(lat1, lat2) && qFuzzyCompare(lon1, lon2)) {
return QPair<double, double>(lat1, lon1);
}
lat1 *= Pi180;
lon1 *= Pi180;
lat2 *= Pi180;
lon2 *= Pi180;
double d = qAcos(qSin(lat1) * qSin(lat2) + qCos(lat1) * qCos(lat2) * qCos(lon1 - lon2));
double A = qSin((1. - f) * d) / qSin(d);
double B = qSin(f * d) / qSin(d);
double x = A * qCos(lat1) * qCos(lon1) + B * qCos(lat2) * qCos(lon2);
double y = A * qCos(lat1) * qSin(lon1) + B * qCos(lat2) * qSin(lon2);
double z = A * qSin(lat1) + B * qSin(lat2);
double rLat = qAtan2(z, sqrt(x * x + y * y));
double rLon = qAtan2(y, x);
return QPair<double, double>(rLat / Pi180, rLon / Pi180);
}
QList<QPair<double, double> > NavData::greatCirclePoints(
double lat1,
double lon1,
double lat2,
double lon2,
double intervalNm
) { // omits last point
QList<QPair<double, double> > result;
if (qFuzzyCompare(lat1, lat2) && qFuzzyCompare(lon1, lon2)) {
return result << QPair<double, double>(lat1, lon1);
}
double fractionIncrement = qMin(1., intervalNm / NavData::distance(lat1, lon1, lat2, lon2));
for (double currentFraction = 0.; currentFraction < 1.; currentFraction += fractionIncrement) {
result.append(greatCircleFraction(lat1, lon1, lat2, lon2, currentFraction));
}
return result;
}
/**
* plot great-circles of lat/lon points on Earth.
* Adds texture coordinates along the way.
**/
void NavData::plotGreatCirclePoints(const QList<QPair<double, double> > &points, bool isReverseTextCoords) {
if (points.isEmpty()) {
return;
}
if (points.size() > 1) {
DoublePair wpOld = points[0];
for (int i = 1; i < points.size(); i++) {
auto subPoints = greatCirclePoints(
wpOld.first, wpOld.second,
points[i].first, points[i].second,
400.
);
for (int h = 0; h < subPoints.count(); h++) {
GLfloat ratio = (GLfloat) (i - 1) / (points.size() - 1) + ((GLfloat) h / subPoints.count()) / (points.size() - 1);
glTexCoord1f(isReverseTextCoords? 1. - ratio: ratio);
VERTEX(subPoints[h].first, subPoints[h].second);
}
wpOld = points[i];
}
}
glTexCoord1f(isReverseTextCoords? 0.: 1.);
VERTEX(points.last().first, points.last().second); // last points gets ommitted by greatCirclePoints by design
}
/** converts (oceanic) points from ARINC424 format
* @return 0 on error
*/
QPair<double, double>* NavData::fromArinc(const QString &str) {
QRegExp arinc("(\\d{2})([NSEW]?)(\\d{2})([NSEW]?)"); // ARINC424 waypoints (strict)
if (arinc.exactMatch(str)) {
auto capturedTexts = arinc.capturedTexts();
if (
!capturedTexts[2].isEmpty()
&& !capturedTexts[4].isEmpty()
) {
return 0;
}
if (
!capturedTexts[2].isEmpty()
|| !capturedTexts[4].isEmpty()
) {
double wLat = capturedTexts[1].toDouble();
double wLon = capturedTexts[3].toDouble();
if (
QRegExp("[SW]").exactMatch(capturedTexts[2])
|| QRegExp("[SW]").exactMatch(capturedTexts[4])
) {
wLat = -wLat;
}
if (!capturedTexts[2].isEmpty()) {
wLon = wLon + 100.;
}
if (
QRegExp("[NW]").exactMatch(capturedTexts[2])
|| QRegExp("[NW]").exactMatch(capturedTexts[4])
) {
wLon = -wLon;
}
return new QPair<double, double>(wLat, wLon);
}
}
return 0;
}
/** converts (oceanic) points to ARINC424 format
* @return null-QString() on error
*/
QString NavData::toArinc(const float _lat, const float _lon) {
if (qAbs(_lat) > 90 || qAbs(_lon) > 180) {
return QString();
}
// bail out if our precision is not sufficient
if (
!qFuzzyCompare(round(_lon), _lon)
|| !qFuzzyCompare(round(_lat), _lat)
) {
return QString();
}
const short lat = _lat, lon = _lon;
QString q; // ARINC 424 quadrant
if (lat > 0) {
if (lon > 0) {
q = "E";
} else {
q = "N";
}
} else {
if (lon > 0) {
q = "S";
} else {
q = "W";
}
}
return QString("%1%2%3%4").
arg(qAbs(lat), 2, 10, QChar('0')).
arg(qAbs(lon) >= 100? q: "").
arg(qAbs(lon) >= 100? qAbs(lon) - 100: qAbs(lon), 2, 10, QChar('0')).
arg(qAbs(lon) >= 100? "": q);
}
/** converts geographic points to "Eurocontrol" (that's just how I call it, it's the basic 40N030W) format
* @return null-QString() on error
*/
QString NavData::toEurocontrol(double lat, double lon, const LatLngPrecission maxPrecision) {
if (qAbs(lat) > 90 || qAbs(lon) > 180) {
return QString();
}
QString latLetter = "N";
if (lat < 0) {
latLetter = "S";
lat = -lat;
}
QString lonLetter = "E";
if (lon < 0) {
lonLetter = "W";
lon = -lon;
}
ushort latDeg = floor(lat);
ushort lonDeg = floor(lon);
if (maxPrecision >= LatLngPrecission::Mins) {
ushort latMin = (int) (lat * 60.) % 60;
ushort lonMin = (int) (lon * 60.) % 60;
if (maxPrecision >= LatLngPrecission::Secs) {
ushort latSec = (int) (lat * 3600.) % 60;
ushort lonSec = (int) (lon * 3600.) % 60;
if (latSec != 0 || lonSec != 0) {
return QString("%1%2%3%4%5%6%7%8")
.arg(latDeg, 2, 10, QChar('0'))
.arg(latMin, 2, 10, QChar('0'))
.arg(latSec, 2, 10, QChar('0'))
.arg(latLetter)
.arg(lonDeg, 3, 10, QChar('0'))
.arg(lonMin, 2, 10, QChar('0'))
.arg(lonSec, 2, 10, QChar('0'))
.arg(lonLetter);
}
}
if (latMin != 0 || lonMin != 0) {
return QString("%1%2%3%4%5%6")
.arg(latDeg, 2, 10, QChar('0'))
.arg(latMin, 2, 10, QChar('0'))
.arg(latLetter)
.arg(lonDeg, 3, 10, QChar('0'))
.arg(lonMin, 2, 10, QChar('0'))
.arg(lonLetter);
}
}
return QString("%1%2%3%4")
.arg(latDeg, 2, 10, QChar('0'))
.arg(latLetter)
.arg(lonDeg, 3, 10, QChar('0'))
.arg(lonLetter);
}
| 15,887
|
C++
|
.cpp
| 452
| 26.920354
| 133
| 0.552541
|
qutescoop/qutescoop
| 33
| 15
| 21
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,638
|
Route.cpp
|
qutescoop_qutescoop/src/Route.cpp
|
#include "Route.h"
#include "Airac.h"
#include "Airport.h"
#include "NavData.h"
Route::Route() {}
Route::~Route() {}
void Route::calculateWaypointsAndDistance() {
Airport* depAirport = NavData::instance()->airports.value(dep, 0);
Airport* destAirport = NavData::instance()->airports.value(dest, 0);
if (depAirport == 0 || destAirport == 0) {
return;
}
QStringList list = route.split(' ', Qt::SkipEmptyParts);
waypoints = Airac::instance()->resolveFlightplan(list, depAirport->lat, depAirport->lon, Airac::ifrMaxWaypointInterval);
Waypoint* depWp = new Waypoint(depAirport->id, depAirport->lat, depAirport->lon);
waypoints.prepend(depWp);
Waypoint* destWp = new Waypoint(destAirport->id, destAirport->lat, destAirport->lon);
waypoints.append(destWp);
waypointsStr = QString();
double dist = 0;
for (int i = 0; i < waypoints.size(); i++) {
if (routeDistance.isEmpty() && i > 0) {
dist += NavData::distance(
waypoints[i - 1]->lat, waypoints[i - 1]->lon,
waypoints[i]->lat, waypoints[i]->lon
);
}
waypointsStr += waypoints[i]->id;
if (i < waypoints.size() - 1) {
waypointsStr += " ";
}
}
// setting distance if it was not set before
if (routeDistance.isEmpty()) {
routeDistance = QString("%1 NM (calculated)").arg(qRound(dist));
}
}
| 1,427
|
C++
|
.cpp
| 37
| 32.216216
| 124
| 0.61922
|
qutescoop/qutescoop
| 33
| 15
| 21
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,639
|
Whazzup.cpp
|
qutescoop_qutescoop/src/Whazzup.cpp
|
#include "Whazzup.h"
#include "Client.h"
#include "GuiMessage.h"
#include "Net.h"
#include "Settings.h"
#include "dialogs/Window.h"
Whazzup* whazzupInstance = 0;
Whazzup* Whazzup::instance() {
if (whazzupInstance == 0) {
whazzupInstance = new Whazzup();
}
return whazzupInstance;
}
Whazzup::Whazzup()
: _replyStatus(0), _replyWhazzup(0), _replyBookings(0) {
_downloadTimer = new QTimer();
_bookingsTimer = new QTimer();
connect(_downloadTimer, &QTimer::timeout, this, &Whazzup::downloadJson3);
connect(_bookingsTimer, &QTimer::timeout, this, &Whazzup::downloadBookings);
connect(this, &Whazzup::needBookings, this, &Whazzup::downloadBookings);
}
Whazzup::~Whazzup() {
if (_downloadTimer != 0) {
delete _downloadTimer;
}
if (_bookingsTimer != 0) {
delete _bookingsTimer;
}
if (_replyStatus != 0) {
delete _replyStatus;
}
if (_replyWhazzup != 0) {
delete _replyWhazzup;
}
if (_replyBookings != 0) {
delete _replyBookings;
}
}
void Whazzup::setStatusLocation(const QString& statusLocation) {
qDebug() << "Downloading network status from\t" << statusLocation;
GuiMessages::progress("statusdownload", "Getting network status...");
_replyStatus = Net::g(statusLocation);
connect(_replyStatus, &QNetworkReply::finished, this, &Whazzup::processStatus);
}
void Whazzup::processStatus() {
qDebug();
disconnect(_replyStatus, &QNetworkReply::finished, this, &Whazzup::processStatus);
// status.vatsim.net uses redirection
QUrl urlRedirect = _replyStatus->attribute(
QNetworkRequest::RedirectionTargetAttribute
).toUrl();
if (!urlRedirect.isEmpty() && urlRedirect != _replyStatus->url()) {
qDebug() << "redirected to" << urlRedirect;
// send new request
if (_replyStatus != 0) {
delete _replyStatus;
}
_replyStatus = Net::g(urlRedirect);
connect(_replyStatus, &QNetworkReply::finished, this, &Whazzup::processStatus);
return;
}
if (_replyStatus->error() != QNetworkReply::NoError) {
GuiMessages::warning(_replyStatus->errorString());
}
if (_replyStatus->bytesAvailable() == 0) {
GuiMessages::warning("Statusfile is empty");
}
_json3Urls.clear();
_metar0Url = "";
_user0Url = "";
QJsonDocument data = QJsonDocument::fromJson(_replyStatus->readAll());
if (data.isNull()) {
GuiMessages::warning("Couldn't parse status. Does the status URL return the old format?");
} else {
QJsonObject json = data.object();
if (json.contains("data") && json["data"].isObject()) {
QJsonObject vatsimDataSources = json["data"].toObject();
if (vatsimDataSources.contains("v3") && vatsimDataSources["v3"].isArray()) {
QJsonArray v3Urls = vatsimDataSources["v3"].toArray();
for (int i = 0; i < v3Urls.size(); ++i) {
if (v3Urls[i].isString()) {
_json3Urls.append(v3Urls[i].toString());
}
}
}
}
if (json.contains("user") && json["user"].isArray()) {
QJsonArray userUrls = json["user"].toArray();
if (userUrls.first() != QJsonValue::Undefined) {
_user0Url = userUrls.first().toString();
}
}
if (json.contains("metar") && json["metar"].isArray()) {
QJsonArray metarUrls = json["metar"].toArray();
if (metarUrls.first() != QJsonValue::Undefined) {
_metar0Url = metarUrls.first().toString();
}
}
}
_lastDownloadTime = QTime();
GuiMessages::remove("statusdownload");
qDebug() << "data.v3[]:" << _json3Urls;
qDebug() << "metar.0:" << _metar0Url;
qDebug() << "user.0:" << _user0Url;
if (_json3Urls.size() == 0) {
GuiMessages::warning("No Whazzup-URLs found. Try again later.");
} else {
downloadJson3();
}
}
void Whazzup::fromFile(QString filename) {
qDebug() << filename;
GuiMessages::progress("whazzupDownload", "Loading Whazzup from file...");
if (_replyWhazzup != 0) {
delete _replyWhazzup;
}
_replyWhazzup = Net::g(QUrl::fromLocalFile(filename));
connect(_replyWhazzup, &QNetworkReply::finished, this, &Whazzup::processWhazzup);
}
void Whazzup::downloadJson3() {
if (_json3Urls.size() == 0) {
setStatusLocation(Settings::statusLocation());
return;
}
_downloadTimer->stop();
QTime now = QTime::currentTime();
const int minIntervalSec = 15;
if (!_lastDownloadTime.isNull() && _lastDownloadTime.secsTo(now) < minIntervalSec) {
GuiMessages::message(
QString("Whazzup checked %1s (less than %2s) ago. Download scheduled.")
.arg(_lastDownloadTime.secsTo(now)).arg(minIntervalSec)
);
_downloadTimer->start((minIntervalSec - _lastDownloadTime.secsTo(now)) * 1000);
return;
}
_lastDownloadTime = now;
QUrl url(_json3Urls[QRandomGenerator::global()->bounded(quint32(_json3Urls.size() - 1))]);
GuiMessages::progress(
"whazzupDownload", QString("Updating whazzup from %1...").
arg(url.toString(QUrl::RemoveUserInfo))
);
if (_replyWhazzup != 0) {
delete _replyWhazzup;
}
_replyWhazzup = Net::g(url);
connect(_replyWhazzup, &QNetworkReply::finished, this, &Whazzup::processWhazzup);
connect(_replyWhazzup, &QNetworkReply::downloadProgress, this, &Whazzup::whazzupProgress);
}
void Whazzup::whazzupProgress(qint64 prog, qint64 tot) {
GuiMessages::progress("whazzupDownload", prog, tot);
}
void Whazzup::processWhazzup() {
GuiMessages::remove("whazzupDownload");
emit whazzupDownloaded();
disconnect(_replyWhazzup, &QNetworkReply::finished, this, &Whazzup::processWhazzup);
disconnect(_replyWhazzup, &QNetworkReply::downloadProgress, this, &Whazzup::whazzupProgress);
if (_replyWhazzup == 0) {
GuiMessages::criticalUserInteraction(
"Buffer unavailable.",
"Whazzup download Error"
);
_downloadTimer->start(30 * 1000); // try again in 30s
return;
}
if (_replyWhazzup->bytesAvailable() == 0) {
GuiMessages::warning("No data in Whazzup.");
_downloadTimer->start(30 * 1000); // try again in 30s
return;
}
if (_replyWhazzup->error() != QNetworkReply::NoError) {
GuiMessages::warning(_replyWhazzup->errorString());
_downloadTimer->start(30 * 1000); // try again in 30s
return;
}
GuiMessages::progress("whazzupProcess", "Processing Whazzup...");
QByteArray* bytes = new QByteArray(_replyWhazzup->readAll());
WhazzupData newWhazzupData(bytes, WhazzupData::WHAZZUP);
if (!newWhazzupData.isNull()) {
if (
!predictedTime.isValid()
&& newWhazzupData.whazzupTime.secsTo(QDateTime::currentDateTimeUtc()) > 60 * 30
) {
GuiMessages::warning("Whazzup data more than 30 minutes old.");
}
if (newWhazzupData.whazzupTime != _data.whazzupTime) {
_data.updateFrom(newWhazzupData);
qDebug() << "Whazzup updated from timestamp" << _data.whazzupTime;
emit newData(true);
if (Settings::saveWhazzupData()) {
// write out Whazzup to a file
QFile out(Settings::dataDirectory(
QString("downloaded/%1_%2.whazzup")
.arg(Settings::downloadNetwork())
.arg(_data.whazzupTime.toString("yyyyMMdd-HHmmss"))
));
if (!out.exists() && out.open(QIODevice::WriteOnly | QIODevice::Text)) {
qDebug() << "Writing Whazzup to" << out.fileName();
out.write(bytes->constData());
out.close();
} else {
qWarning() << "Could not write Whazzup to disk" << out.fileName();
}
}
} else {
GuiMessages::message(
QString("We already have Whazzup with that Timestamp: %1")
.arg(_data.whazzupTime.toString("ddd MM/dd HHmm'z'"))
);
}
}
if (Settings::downloadPeriodically()) {
const int serverNextUpdateInSec = QDateTime::currentDateTimeUtc().secsTo(_data.updateEarliest);
if (
_data.updateEarliest.isValid()
&& (Settings::downloadInterval() < serverNextUpdateInSec)
) {
_downloadTimer->start(serverNextUpdateInSec);
qDebug() << "correcting next update, will update in"
<< serverNextUpdateInSec << "s to respect the server's minimum interval";
} else {
_downloadTimer->start(Settings::downloadInterval() * 1000);
}
}
GuiMessages::remove("whazzupProcess");
}
void Whazzup::downloadBookings() {
if (!Settings::downloadBookings()) {
return;
}
QUrl url(Settings::bookingsLocation());
_bookingsTimer->stop();
GuiMessages::progress(
"bookingsDownload",
QString("Updating ATC Bookings from %1...")
.arg(url.toString(QUrl::RemoveUserInfo))
);
if (_replyBookings != 0) {
delete _replyBookings;
}
_replyBookings = Net::g(url);
connect(_replyBookings, &QNetworkReply::finished, this, &Whazzup::processBookings);
connect(_replyBookings, &QNetworkReply::downloadProgress, this, &Whazzup::bookingsProgress);
}
void Whazzup::bookingsProgress(qint64 prog, qint64 tot) {
GuiMessages::progress("bookingsDownload", prog, tot);
}
void Whazzup::processBookings() {
qDebug();
GuiMessages::remove("bookingsDownload");
disconnect(_replyBookings, &QNetworkReply::finished, this, &Whazzup::processBookings);
disconnect(_replyBookings, &QNetworkReply::downloadProgress, this, &Whazzup::bookingsProgress);
qDebug() << "deleting buffer";
if (_replyBookings == 0) {
GuiMessages::criticalUserInteraction(
"Buffer unavailable.",
"Booking download Error"
);
return;
}
if (_replyBookings->bytesAvailable() == 0) {
GuiMessages::warning("No data in Bookings.");
return;
}
if (_replyBookings->error() != QNetworkReply::NoError) {
GuiMessages::warning(_replyBookings->errorString());
return;
}
if (Settings::downloadBookings() && Settings::bookingsPeriodically()) {
_bookingsTimer->start(Settings::bookingsInterval() * 60 * 1000);
}
GuiMessages::progress("bookingsProcess", "Processing Bookings...");
QByteArray* bytes = new QByteArray(_replyBookings->readAll());
WhazzupData newBookingsData(bytes, WhazzupData::ATCBOOKINGS);
if (!newBookingsData.isNull()) {
qDebug() << "step 2";
if (newBookingsData.bookingsTime.secsTo(QDateTime::currentDateTimeUtc()) > 60 * 60 * 3) {
GuiMessages::warning("Bookings data more than 3 hours old.");
}
if (newBookingsData.bookingsTime != _data.bookingsTime) {
qDebug() << "will call updateFrom()";
_data.updateFrom(newBookingsData);
qDebug() << "Bookings updated from timestamp"
<< _data.bookingsTime;
QFile out(Settings::dataDirectory(
QString("downloaded/%1_%2.bookings")
.arg(Settings::downloadNetwork())
.arg(_data.bookingsTime.toString("yyyyMMdd-HHmmss"))
));
if (!out.exists() && out.open(QIODevice::WriteOnly | QIODevice::Text)) {
qDebug() << "writing bookings to" << out.fileName();
out.write(bytes->constData());
out.close();
} else {
qWarning() << "Could not write Bookings to disk"
<< out.fileName();
}
// from now on we want to redownload when the user triggers a network update
connect(Window::instance()->actionDownload, &QAction::triggered, this, &Whazzup::downloadBookings);
emit newData(true);
} else {
GuiMessages::message(
QString("We already have bookings with that timestamp: %1")
.arg(_data.bookingsTime.toString("ddd MM/dd HHmm'z'"))
);
}
}
GuiMessages::remove("bookingsProcess");
qDebug() << "-- finished";
}
QString Whazzup::userUrl(const QString& id) const {
if (_user0Url.isEmpty() || !Client::isValidID(id)) {
return QString();
}
return _user0Url + "?id=" + id;
}
QString Whazzup::metarUrl(const QString& id) const {
if (_metar0Url.isEmpty()) {
return QString();
}
return _metar0Url + "?id=" + id;
}
void Whazzup::setPredictedTime(QDateTime predictedTime) {
if (this->predictedTime != predictedTime) {
qDebug() << "predictedTime=" << predictedTime
<< "data.whazzupTime=" << _data.whazzupTime;
GuiMessages::progress("warpProcess", "Calculating Warp...");
this->predictedTime = predictedTime;
if (Settings::downloadBookings() && !_data.bookingsTime.isValid()) {
emit needBookings();
}
if (predictedTime == _data.whazzupTime) {
qDebug() << "predictedTime == data.whazzupTime"
<< "(no need to predict, we have it already :) )";
_predictedData = _data;
} else {
_predictedData.updateFrom(WhazzupData(predictedTime, _data)); // or .assignFrom()?
}
GuiMessages::remove("warpProcess");
emit newData(true);
}
}
QList <QPair <QDateTime, QString> > Whazzup::downloadedWhazzups() const {
// Process directory
QStringList list = QDir(Settings::dataDirectory("downloaded/")).entryList(
QStringList(QString("%1_*.whazzup").arg(Settings::downloadNetwork())),
QDir::Files | QDir::Readable
); // getting all *.whazzup
list.sort();
QList <QPair <QDateTime, QString> > returnList;
foreach (const QString filename, list) {
QRegExp dtRe = QRegExp("\\.*_(\\d{8}-\\d{6})"); // dateTime: 20110301-191050
if (dtRe.indexIn(filename) > 0) {
QDateTime dt = QDateTime::fromString(dtRe.cap(1), "yyyyMMdd-HHmmss");
dt.setTimeSpec(Qt::UTC);
returnList.append(
QPair<QDateTime, QString>(
dt,
Settings::dataDirectory(
QString("downloaded/%1").
arg(filename)
)
)
);
}
}
return returnList;
}
| 14,769
|
C++
|
.cpp
| 367
| 31.577657
| 111
| 0.603638
|
qutescoop/qutescoop
| 33
| 15
| 21
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,640
|
Waypoint.cpp
|
qutescoop_qutescoop/src/Waypoint.cpp
|
#include "Waypoint.h"
#include "Airac.h"
#include "NavData.h"
Waypoint::Waypoint(const QStringList& fields)
: MapObject() {
if (fields.size() != 6) {
QMessageLogger("earth_fix.dat", 0, QT_MESSAGELOG_FUNC).critical()
<< fields << ": Expected 6 fields";
return;
}
bool ok;
lat = fields[0].toDouble(&ok);
if (!ok) {
QMessageLogger("earth_fix.dat", 0, QT_MESSAGELOG_FUNC).critical()
<< fields << ": unable to parse lat";
return;
}
lon = fields[1].toDouble(&ok);
if (!ok) {
QMessageLogger("earth_fix.dat", 0, QT_MESSAGELOG_FUNC).critical()
<< fields << ": unable to parse lon";
return;
}
id = fields[2];
regionCode = fields[4];
}
Waypoint::Waypoint(const QString& id, const double lat, const double lon)
: MapObject() {
this->id = id;
this->lat = lat;
this->lon = lon;
}
Waypoint::~Waypoint() {}
QString Waypoint::mapLabel() const {
return id;
}
QStringList Waypoint::mapLabelSecondaryLinesHovered() const {
return {
// airwaysString().split("\n")
};
}
QString Waypoint::toolTip() const {
return QString("%1 (%2)")
.arg(id, NavData::toEurocontrol(lat, lon, LatLngPrecission::Secs));
}
int Waypoint::type() {
return 0;
}
const QString Waypoint::airwaysString() const {
QStringList ret;
auto airac = Airac::instance(false);
if (airac == 0) {
return { };
}
foreach (const auto &awyList, airac->airways) {
foreach (const auto &a, awyList) {
if (a->waypoints().contains((Waypoint*) this)) {
ret << a->name;
}
}
}
return ret.join("\n");
}
| 1,720
|
C++
|
.cpp
| 63
| 21.666667
| 75
| 0.586837
|
qutescoop/qutescoop
| 33
| 15
| 21
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,641
|
PilotDetails.cpp
|
qutescoop_qutescoop/src/dialogs/PilotDetails.cpp
|
#include "PilotDetails.h"
#include "Window.h"
#include "../Settings.h"
#include "../Whazzup.h"
//singleton instance
PilotDetails* pilotDetails = 0;
PilotDetails* PilotDetails::instance(bool createIfNoInstance, QWidget* parent) {
if (pilotDetails == 0) {
if (createIfNoInstance) {
if (parent == 0) {
parent = Window::instance();
}
pilotDetails = new PilotDetails(parent);
}
}
return pilotDetails;
}
// destroys a singleton instance
void PilotDetails::destroyInstance() {
delete pilotDetails;
pilotDetails = 0;
}
PilotDetails::PilotDetails(QWidget* parent)
: ClientDetails(parent),
_pilot(0) {
setupUi(this);
setWindowFlags(windowFlags() ^= Qt::WindowContextHelpButtonHint);
connect(buttonShowOnMap, &QAbstractButton::clicked, this, &ClientDetails::showOnMap);
auto preferences = Settings::dialogPreferences(m_preferencesName);
if (!preferences.size.isNull()) {
resize(preferences.size);
}
if (!preferences.pos.isNull()) {
move(preferences.pos);
}
if (!preferences.geometry.isNull()) {
restoreGeometry(preferences.geometry);
}
}
void PilotDetails::refresh(Pilot* pilot) {
if (pilot != 0) {
_pilot = pilot;
} else {
_pilot = Whazzup::instance()->whazzupData().findPilot(callsign);
}
if (_pilot == 0) {
hide();
return;
}
setMapObject(_pilot);
setWindowTitle(_pilot->toolTip());
// Pilot Information
lblPilotInfo->setText(
QString("<strong>%1</strong>%2")
.arg(
_pilot->displayName(true),
_pilot->detailInformation().isEmpty()? "": ", " + _pilot->detailInformation()
)
);
if (_pilot->server.isEmpty()) {
lblConnected->setText(QString("<i>not connected</i>"));
} else {
lblConnected->setText(QString("on %1 for %2").arg(_pilot->server, _pilot->onlineTime()));
}
buttonShowOnMap->setEnabled(_pilot->lat != 0 || _pilot->lon != 0);
// Aircraft Information
lblAircraft->setText(
QString("<a href='https://contentzone.eurocontrol.int/aircraftperformance/default.aspx?ICAOFilter=%1'>%1</a>").arg(_pilot->planAircraftShort.toHtmlEscaped())
);
lblAircraft->setToolTip(
QString("Opens performance data in web browser.<br>Raw data: %1 – FAA: %2").arg(_pilot->planAircraftFull, _pilot->planAircraftFaa)
);
if (_pilot->airline != 0) {
lblAirline->setText(_pilot->airline->label());
lblAirline->setToolTip(_pilot->airline->toolTip());
} else {
lblAirline->setText("n/a");
lblAirline->setToolTip("");
}
lblAltitude->setText(_pilot->humanAlt());
lblAltitude->setToolTip(
QString("local QNH %1 inHg / %2 hPa (%3 ft)")
.arg(_pilot->qnh_inHg)
.arg(_pilot->qnh_mb)
.arg(_pilot->altitude)
);
lblGroundspeed->setText(QString("%1 kt").arg(_pilot->groundspeed));
if (_pilot->transponderAssigned != "0000" && _pilot->transponderAssigned != "") {
if (_pilot->transponderAssigned != _pilot->transponder) {
lblSquawk->setText(QString("%1 !").arg(_pilot->transponder, _pilot->transponderAssigned));
lblSquawk->setToolTip(QString("ATC assigned: %1").arg(_pilot->transponderAssigned));
} else {
lblSquawk->setText(QString("%1 =").arg(_pilot->transponder));
lblSquawk->setToolTip("ATC assigned squawk set");
}
} else {
lblSquawk->setText(QString("%1").arg(_pilot->transponder));
lblSquawk->setToolTip("no ATC assigned squawk");
}
// flight status
groupStatus->setTitle(QString("Status: %1").arg(_pilot->flightStatusShortString()));
lblFlightStatus->setText(_pilot->flightStatusString());
// flight plan
groupFp->setVisible(!_pilot->planFlighttype.isEmpty()); // hide for Bush pilots
groupFp->setTitle(
QString("Flightplan (%1)")
.arg(_pilot->planFlighttypeString())
);
buttonFrom->setEnabled(_pilot->depAirport() != 0);
buttonFrom->setText(_pilot->depAirport() != 0? _pilot->depAirport()->toolTip(): _pilot->planDep);
buttonDest->setEnabled(_pilot->destAirport() != 0);
buttonDest->setText(_pilot->destAirport() != 0? _pilot->destAirport()->toolTip(): _pilot->planDest);
buttonAlt->setEnabled(_pilot->altAirport() != 0);
buttonAlt->setText(_pilot->altAirport() != 0? _pilot->altAirport()->toolTip(): _pilot->planAltAirport);
lblPlanEtd->setText(_pilot->etd().toString("HHmm"));
lblPlanEta->setText(_pilot->etaPlan().toString("HHmm"));
lblFuel->setText(QTime(_pilot->planFuel_hrs, _pilot->planFuel_mins).toString("H:mm"));
static QRegularExpression routeSlashAmendRe("([^/ ]+)/([^/ ]+)");
lblRoute->setText(
QString("<code>%1</code>").arg(
_pilot->planRoute.toHtmlEscaped().trimmed().replace(
routeSlashAmendRe,
"\\1<span style='color: " + Settings::lightTextColor().name(QColor::HexArgb) + "'>/<small>\\2</small></span>"
)
)
);
lblPlanTas->setText(QString("N%1").arg(_pilot->planTasInt()));
lblPlanFl->setText(QString("F%1").arg(_pilot->defuckPlanAlt(_pilot->planAlt) / 100));
lblPlanEte->setText(QString("%1").arg(QTime(_pilot->planEnroute_hrs, _pilot->planEnroute_mins).toString("H:mm")));
static QRegularExpression rmkSlashAmendRe("([ ]?[^ ]+)/");
lblRemarks->setText(
QString("<code>%1</code>").arg(
_pilot->planRemarks.toHtmlEscaped().trimmed().replace(
rmkSlashAmendRe,
// we make use of the error-tolerant HTML-parser...
"</small><b>\\1</b><span style='color: " + Settings::lightTextColor().name(QColor::HexArgb) + "'>/</span><small>"
)
)
);
// check if we know userId
bool invalidID = !(_pilot->hasValidID());
buttonAddFriend->setDisabled(invalidID);
pbAlias->setDisabled(invalidID);
buttonAddFriend->setText(_pilot->isFriend()? "remove &friend": "add &friend");
// check if we know position
buttonShowOnMap->setDisabled(qFuzzyIsNull(_pilot->lon) && qFuzzyIsNull(_pilot->lat));
// routes
bool isShowRouteExternal = Settings::showRoutes()
|| (_pilot->depAirport() != 0 && _pilot->depAirport()->showRoutes)
|| (_pilot->destAirport() != 0 && _pilot->destAirport()->showRoutes);
if (!isShowRouteExternal && !_pilot->showRoute) {
cbPlotRoute->setCheckState(Qt::Unchecked);
}
if (isShowRouteExternal && !_pilot->showRoute) {
cbPlotRoute->setCheckState(Qt::PartiallyChecked);
}
if (_pilot->showRoute) {
cbPlotRoute->setCheckState(Qt::Checked);
}
if (_pilot->showRoute || isShowRouteExternal) {
lblPlotStatus->setText(
QString(
"<span style='color: "
+ Settings::lightTextColor().name(QColor::HexArgb)
+ "'>waypoints (calculated): <small><code>%1</code></small></span>"
).arg(_pilot->routeWaypointsString())
);
}
lblPlotStatus->setVisible(_pilot->showRoute || isShowRouteExternal);
}
void PilotDetails::on_buttonDest_clicked() {
if (_pilot->destAirport() != 0 && _pilot->destAirport()->hasPrimaryAction()) {
_pilot->destAirport()->primaryAction();
}
}
void PilotDetails::on_buttonAlt_clicked() {
if (_pilot->altAirport() != 0 && _pilot->altAirport()->hasPrimaryAction()) {
_pilot->altAirport()->primaryAction();
}
}
void PilotDetails::on_buttonFrom_clicked() {
if (_pilot->depAirport() != 0 && _pilot->depAirport()->hasPrimaryAction()) {
_pilot->depAirport()->primaryAction();
}
}
void PilotDetails::on_buttonAddFriend_clicked() {
friendClicked();
refresh();
}
void PilotDetails::on_cbPlotRoute_clicked(bool checked) {
_pilot->showRoute = checked;
if (Window::instance(false) != 0) {
Window::instance()->mapScreen->glWidget->invalidatePilots();
}
refresh();
}
void PilotDetails::closeEvent(QCloseEvent* event) {
Settings::setDialogPreferences(
m_preferencesName,
Settings::DialogPreferences {
.size = size(),
.pos = pos(),
.geometry = saveGeometry()
}
);
event->accept();
}
void PilotDetails::on_pbAlias_clicked() {
if (_pilot->showAliasDialog(this)) {
refresh();
}
}
| 8,454
|
C++
|
.cpp
| 212
| 33.117925
| 165
| 0.626782
|
qutescoop/qutescoop
| 33
| 15
| 21
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.