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,537,464
Singleton.h
TheStarport_FLHook/include/ext/Singleton.h
#pragma once #include <memory> template<typename T> class Singleton { public: static T* i(std::unique_ptr<T>* o = nullptr) { static std::unique_ptr<T> i = std::unique_ptr<T>(new T()); if (o) { i = std::move(*o); } return i.get(); } static T& ir(std::unique_ptr<T>* o = nullptr) { return *i(o); } static const T* c() { return i(); } };
361
C++
.h
18
17.611111
64
0.60767
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,466
Structs.hpp
TheStarport_FLHook/include/Tools/Structs.hpp
#pragma once #include "plugin.h" struct HookEntry { FARPROC fpProc; long dwRemoteAddress; FARPROC fpOldProc; }; struct CARGO_INFO { uint iId; int iCount; uint iArchId; float fStatus; bool bMission; bool bMounted; CacheString hardpoint; }; // money stuff struct MONEY_FIX { std::wstring character; uint uAmount; bool operator==(MONEY_FIX mf1) const { if (!character.compare(mf1.character)) return true; return false; }; }; // ignore struct IGNORE_INFO { std::wstring character; std::wstring wscFlags; }; // resolver struct RESOLVE_IP { ClientId client; uint iConnects; std::wstring wscIP; std::wstring wscHostname; }; struct CLIENT_INFO { // kill msgs uint ship; uint shipOld; mstime tmSpawnTime; DamageList dmgLast; // money cmd std::list<MONEY_FIX> lstMoneyFix; // anticheat uint iTradePartner; // change cruise disruptor behaviour bool bCruiseActivated; bool bThrusterActivated; bool bEngineKilled; bool bTradelane; // idle kicks uint iBaseEnterTime; uint iCharMenuEnterTime; // msg, wait and kick mstime tmKickTime; // eventmode uint iLastExitedBaseId; bool bDisconnected; // f1 laming bool bCharSelected; mstime tmF1Time; mstime tmF1TimeDisconnect; // ignore usercommand std::list<IGNORE_INFO> lstIgnore; // user settings DIEMSGTYPE dieMsg; CHATSIZE dieMsgSize; CHATSTYLE dieMsgStyle; CHATSIZE chatSize; CHATSTYLE chatStyle; // bans uint iConnects; // incremented when player connects // Group uint iGroupId; // other std::wstring wscHostname; bool bSpawnProtected; bool bUseServersideHitDetection; // used by AC Plugin // Your randomly assigned formation tag, e.g. Navy Lambda 1-6 uint formationNumber1; uint formationNumber2; uint formationTag; }; // taken from directplay typedef struct _DPN_CONNECTION_INFO { DWORD dwSize; DWORD dwRoundTripLatencyMS; DWORD dwThroughputBPS; DWORD dwPeakThroughputBPS; DWORD dwBytesSentGuaranteed; DWORD dwPacketsSentGuaranteed; DWORD dwBytesSentNonGuaranteed; DWORD dwPacketsSentNonGuaranteed; DWORD dwBytesRetried; DWORD dwPacketsRetried; DWORD dwBytesDropped; DWORD dwPacketsDropped; DWORD dwMessagesTransmittedHighPriority; DWORD dwMessagesTimedOutHighPriority; DWORD dwMessagesTransmittedNormalPriority; DWORD dwMessagesTimedOutNormalPriority; DWORD dwMessagesTransmittedLowPriority; DWORD dwMessagesTimedOutLowPriority; DWORD dwBytesReceivedGuaranteed; DWORD dwPacketsReceivedGuaranteed; DWORD dwBytesReceivedNonGuaranteed; DWORD dwPacketsReceivedNonGuaranteed; DWORD dwMessagesReceived; } DPN_CONNECTION_INFO, *PDPN_CONNECTION_INFO; struct PlayerInfo { uint client; std::wstring character; std::wstring wscBase; std::wstring wscSystem; uint iSystem; uint ship; DPN_CONNECTION_INFO connectionInfo; std::wstring wscIP; std::wstring wscHostname; }; struct BaseHealth { float currentHealth; float maxHealth; }; struct PatchInfoEntry { ulong pAddress; void* pNewValue; uint iSize; void* pOldValue; bool bAlloced; }; struct PatchInfo { const char* szBinName; ulong pBaseAddress; PatchInfoEntry piEntries[128]; }; struct DataMarketItem { uint iArchId; float fRep; }; struct BaseInfo { uint baseId; std::string scBasename; uint iObjectId; bool bDestroyed; std::list<DataMarketItem> lstMarketMisc; }; struct GroupMember { ClientId client; std::wstring character; }; struct SpecialChatIds { enum : uint { CONSOLE = 0, PLAYER_MIN = 1, PLAYER_MAX = 249, SPECIAL_BASE = 0x10000, UNIVERSE = SPECIAL_BASE | 0, SYSTEM = SPECIAL_BASE | 1, LOCAL = SPECIAL_BASE | 2, GROUP = SPECIAL_BASE | 3, GROUP_EVENT = SPECIAL_BASE | 4 }; }; struct SystemInfo { /** The system nickname */ std::string sysNick; /** The system id */ uint systemId; /** The system scale */ float scale; }; struct TransformMatrix { float d[4][4]; }; struct Zone { /** The system nickname */ std::string sysNick; /** The zone nickname */ std::string zoneNick; /** The id of the system for this zone */ uint systemId; /** The zone transformation matrix */ TransformMatrix transform; /** The zone ellipsoid size */ Vector size; /** The zone position */ Vector pos; /** The damage this zone causes per second */ int damage; /** Is this an encounter zone */ bool encounter; }; class JumpPoint { public: /** The system nickname */ std::string sysNick; /** The jump point nickname */ std::string jumpNick; /** The jump point destination system nickname */ std::string jumpDestSysNick; /** The id of the system for this jump point. */ uint System; /** The id of the jump point. */ uint jumpId; /** The jump point destination system id */ uint jumpDestSysId; }; struct LootableZone { /** The zone nickname */ std::string zoneNick; /** The id of the system for this lootable zone */ uint systemId; /** The nickname and arch id of the loot dropped by the asteroids */ std::string lootNick; uint iLootId; /** The arch id of the crate the loot is dropped in */ uint iCrateId; /** The minimum number of loot items to drop */ uint iMinLoot; /** The maximum number of loot items to drop */ uint iMaxLoot; /** The drop difficultly */ uint iLootDifficulty; /** The lootable zone ellipsoid size */ Vector size; /** The lootable zone position */ Vector pos; }; struct Light { std::string nickname; uint archId; float bulbSize; float glowSize; float intensity; Vector glowColor; Vector color; Vector minColor; bool dockingLight; bool alwaysOn; float flareConeMin; float flareConeMax; int lightSourceCone; bool blinks; float delay; float blinkDuration; };
5,611
C++
.h
273
18.520147
69
0.777778
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,467
Detour.hpp
TheStarport_FLHook/include/Tools/Detour.hpp
#pragma once #include <Windows.h> #include <string> #include <memory> #include <array> template<typename CallSig> class FunctionDetour final { CallSig originalFunc; PBYTE data; std::allocator<unsigned char> alloc; FunctionDetour(const FunctionDetour&) = delete; FunctionDetour& operator=(FunctionDetour) = delete; public: CallSig GetOriginalFunc() { return originalFunc; } explicit FunctionDetour(CallSig origFunc) : originalFunc(origFunc) { data = alloc.allocate(5); } ~FunctionDetour() { alloc.deallocate(data, 5); } void Detour(const CallSig hookedFunc) { DWORD dwOldProtection = 0; // Create a DWORD for VirtualProtect calls to allow us to write. std::array<byte, 5> bPatch; // We need to change 5 bytes and I'm going to use memcpy so this is the simplest way. bPatch[0] = 0xE9; // Set the first byte of the byte array to the op code for the JMP instruction. VirtualProtect((void*)originalFunc, 5, PAGE_EXECUTE_READWRITE, &dwOldProtection); // Allow us to write to the memory we need to change DWORD dwRelativeAddress = (DWORD)hookedFunc - (DWORD)originalFunc - 5; // Calculate the relative JMP address. memcpy(&bPatch[1], &dwRelativeAddress, 4); // Copy the relative address to the byte array. memcpy(data, originalFunc, 5); memcpy(originalFunc, bPatch.data(), 5); // Change the first 5 bytes to the JMP instruction. VirtualProtect((void*)originalFunc, 5, dwOldProtection, nullptr); // Set the protection back to what it was. } void UnDetour() { DWORD dwOldProtection = 0; // Create a DWORD for VirtualProtect calls to allow us to write. VirtualProtect((void*)originalFunc, 5, PAGE_EXECUTE_READWRITE, &dwOldProtection); // Allow us to write to the memory we need to change memcpy(originalFunc, data, 5); VirtualProtect((void*)originalFunc, 5, dwOldProtection, nullptr); // Set the protection back to what it was. } };
2,013
C++
.h
37
52.108108
148
0.703553
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,468
Concepts.hpp
TheStarport_FLHook/include/Tools/Concepts.hpp
#pragma once #include <string> template<typename T> concept StringRestriction = std::is_same_v<std::string, T> || std::is_same_v<std::wstring, T>; template<typename ... T> concept AtLeastOne = (sizeof...(T) > 0); template<typename T> concept IsNumeric = std::is_integral_v<T> || std::is_floating_point_v<T>; template<typename T> concept IsSignedIntegral = IsNumeric<T> && std::is_signed_v<T>; template<typename T> concept IsUnsignedIntegral = IsNumeric<T> && !IsSignedIntegral<T>; template<typename Base, typename Derrived> concept IsDerivedFrom = std::derived_from<Derrived, Base>; template<typename Base, typename Derrived> concept IsBaseOf = std::is_base_of_v<Base, Derrived>;
686
C++
.h
16
41.5
94
0.759036
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,469
Hk.hpp
TheStarport_FLHook/include/Tools/Hk.hpp
#pragma once #include "Typedefs.hpp" #include "Enums.hpp" #include "Constexpr.hpp" #include "Macros.hpp" extern DLL st6_malloc_t st6_malloc; extern DLL st6_free_t st6_free; #define ST6_ALLOCATION_DEFINED #include "FLCore/FLCoreCommon.h" #include "FLCore/FLCoreServer.h" #include "FLCore/FLCoreRemoteClient.h" #include "FLCore/FLCoreDALib.h" #include <ext/Singleton.h> #include "Structs.hpp" #include "Concepts.hpp" #include "Deps.hpp" struct CARGO_INFO; #pragma once namespace Hk { namespace Time { DLL uint GetUnixSeconds(); DLL uint GetUnixMiliseconds(); template<typename T> std::chrono::microseconds ToMicroseconds(T duration) { return std::chrono::duration_cast<std::chrono::microseconds>(duration); } template<typename T> std::chrono::milliseconds ToMilliseconds(T duration) { return std::chrono::duration_cast<std::chrono::milliseconds>(duration); } template<typename T> std::chrono::seconds ToSeconds(T duration) { return std::chrono::duration_cast<std::chrono::seconds>(duration); } template<typename T> std::chrono::minutes ToMinutes(T duration) { return std::chrono::duration_cast<std::chrono::minutes>(duration); } template<typename T> std::chrono::hours ToHours(T duration) { return std::chrono::duration_cast<std::chrono::hours>(duration); } template<typename T> std::chrono::nanoseconds ToNanoseconds(T duration) { return std::chrono::duration_cast<std::chrono::nanoseconds>(duration); } } // namespace Time namespace Client { /** * Gets the current client id of the account. * @param acc CAccount * @returns On success : Client id of the active user of the account. * @returns On fail : [PlayerNotLoggedIn] The function could not find a client id associated with the account id. */ DLL cpp::result<const uint, Error> GetClientIdFromAccount(const CAccount* acc); DLL std::wstring GetAccountIdByClientID(ClientId client); DLL CAccount* GetAccountByClientID(ClientId client); /** * Gets the current client id of the character. * @param character Wide string of the character name * @returns On success : current client Id associated with that character name * @returns On fail : [CharacterDoesNotExist] The function could not find a client id associated with this character name. */ DLL cpp::result<const uint, Error> GetClientIdFromCharName(const std::wstring& character); /** * Checks to see if the client Id is valid * @param client Client Id * @returns If Valid: true * @returns If Not Valid: false */ DLL bool IsValidClientID(ClientId client); /** * Gets the account of the character * @param character Wide string of the character name * @returns On success : the account Id for that character * @returns On fail : [CharacterDoesNotExist] The function could not find the account id associated with this character name. */ DLL cpp::result<CAccount*, Error> GetAccountByCharName(const std::wstring& character); /** * Gets the account id in a wide string * @param acc The account * @returns On success : wide string of account Id * @returns On fail : [CannotGetAccount] The function could not find the account. */ DLL cpp::result<const std::wstring, Error> GetAccountID(CAccount* acc); /** * Gets the account id in a wide string * @param fileName The account * @returns On success : wide string of account Id * @returns On fail : [CannotGetAccount] The function could not find the account. */ DLL bool IsEncoded(const std::string& fileName); DLL bool IsInCharSelectMenu(const uint& player); DLL cpp::result<const std::wstring, Error> GetCharacterNameByID(ClientId& client); DLL cpp::result<const uint, Error> ResolveID(const std::wstring& player); DLL cpp::result<ClientId, Error> ResolveShortCut(const std::wstring& wscShortcut); DLL cpp::result<ClientId, Error> GetClientIdByShip(ShipId ship); DLL std::wstring GetAccountDirName(const CAccount* acc); DLL cpp::result<const std::wstring, Error> GetCharFileName(const std::variant<uint, std::wstring>& player); DLL cpp::result<const std::wstring, Error> GetCharFileName(const std::variant<uint, std::wstring>& player, bool returnValueIfNoFile); DLL cpp::result<const std::wstring, Error> GetBaseNickByID(uint baseId); DLL cpp::result<const std::wstring, Error> GetPlayerSystem(ClientId client); DLL cpp::result<const std::wstring, Error> GetSystemNickByID(uint systemId); DLL std::vector<uint> getAllPlayersInSystem(SystemId system); DLL cpp::result<void, Error> LockAccountAccess(CAccount* acc, bool bKick); DLL cpp::result<void, Error> UnlockAccountAccess(CAccount* acc); DLL cpp::result<void, Error> PlaySoundEffect(ClientId client, uint soundId); DLL void GetItemsForSale(uint baseId, std::list<uint>& lstItems); DLL cpp::result<IObjInspectImpl*, Error> GetInspect(ClientId client); DLL EngineState GetEngineState(ClientId client); DLL EquipmentType GetEqType(Archetype::Equipment* eq); } // namespace Client namespace Math { /** * Computes the difference between two points in 3d space, * @param v1 3d vector 1 * @param v2 3d vector 2 * @returns a scalar of the distance between point v2 and v1 */ DLL float Distance3D(Vector v1, Vector v2); /** * See Distance3D for more information * @see Distance3D */ DLL cpp::result<float, Error> Distance3DByShip(uint ship1, uint ship2); /** * Converts a 3x3 rotation matrix into an equivalent quaternion. */ DLL Quaternion MatrixToQuaternion(const Matrix& m); template<typename Str> Str VectorToSectorCoord(uint systemId, Vector vPos); template DLL std::string VectorToSectorCoord(uint systemId, Vector vPos); template DLL std::wstring VectorToSectorCoord(uint systemId, Vector vPos); DLL float Degrees(float rad); DLL Vector MatrixToEuler(const Matrix& mat); DLL uint RgbToBgr(uint color); DLL std::wstring UintToHexString(uint number, uint width, bool addPrefix = false); } // namespace Math namespace Message { DLL cpp::result<void, Error> Msg(const std::variant<uint, std::wstring>& player, const std::wstring& wscMessage); DLL cpp::result<void, Error> MsgS(const std::variant<std::wstring, uint>& system, const std::wstring& wscMessage); DLL cpp::result<void, Error> MsgU(const std::wstring& wscMessage); DLL cpp::result<void, Error> FMsgEncodeXML(const std::wstring& wscXml, char* szBuf, uint iSize, uint& iRet); DLL void FMsgSendChat(ClientId client, char* szBuf, uint iSize); DLL cpp::result<void, Error> FMsg(ClientId client, const std::wstring& wscXML); DLL cpp::result<void, Error> FMsg(const std::variant<uint, std::wstring>& player, const std::wstring& wscXML); DLL cpp::result<void, Error> FMsgS(const std::variant<std::wstring, uint>& system, const std::wstring& wscXML); DLL cpp::result<void, Error> FMsgU(const std::wstring& wscXML); DLL std::wstring FormatMsg(MessageColor color, MessageFormat format, const std::wstring& msg); DLL std::wstring GetWStringFromIdS(uint iIdS); DLL void LoadStringDLLs(); DLL void UnloadStringDLLs(); DLL cpp::result<void, Error> FormatSendChat(uint iToClientId, const std::wstring& wscSender, const std::wstring& text, const std::wstring& textColor); DLL void SendGroupChat(uint iFromClientId, const std::wstring& text); DLL void SendLocalSystemChat(uint iFromClientId, const std::wstring& text); DLL cpp::result<void, Error> SendPrivateChat(uint iFromClientId, uint iToClientId, const std::wstring& text); DLL void SendSystemChat(uint iFromClientId, const std::wstring& text); } // namespace Message namespace Player { DLL cpp::result<void, Error> AddToGroup(ClientId client, uint iGroupId); DLL cpp::result<const uint, Error> GetGroupID(ClientId client); DLL cpp::result<const uint, Error> GetCash(const std::variant<uint, std::wstring>& player); DLL cpp::result<void, Error> AddCash(const std::variant<uint, std::wstring>& player, uint uAmount); DLL cpp::result<void, Error> RemoveCash(const std::variant<uint, std::wstring>& player, uint uAmount); DLL cpp::result<void, Error> AdjustCash(const std::variant<uint, std::wstring>& player, int iAmount); DLL cpp::result<void, Error> Kick(const std::variant<uint, std::wstring>& player); DLL cpp::result<void, Error> KickReason(const std::variant<uint, std::wstring>& player, const std::wstring& wscReason); DLL cpp::result<void, Error> Ban(const std::variant<uint, std::wstring>& player, bool bBan); DLL cpp::result<void, Error> TempBan(const std::variant<uint, std::wstring>& player, uint duration); DLL cpp::result<void, Error> Beam(const std::variant<uint, std::wstring>& player, const std::variant<uint, std::wstring>& base); DLL cpp::result<void, Error> SaveChar(const std::variant<uint, std::wstring>& player); DLL cpp::result<const std::list<CARGO_INFO>, Error> EnumCargo(const std::variant<uint, std::wstring>& player, int& iRemainingHoldSize); DLL cpp::result<void, Error> RemoveCargo(const std::variant<uint, std::wstring>& player, ushort cargoId, int count); DLL cpp::result<void, Error> AddCargo(const std::variant<uint, std::wstring>& player, uint iGoodId, int iCount, bool bMission); DLL cpp::result<void, Error> AddCargo(const std::variant<uint, std::wstring>& player, const std::wstring& wscGood, int iCount, bool bMission); DLL cpp::result<void, Error> Rename(const std::variant<uint, std::wstring>& player, const std::wstring& wscNewCharname, bool bOnlyDelete); DLL cpp::result<void, Error> MsgAndKick(ClientId client, const std::wstring& wscReason, uint iIntervall); DLL cpp::result<void, Error> Kill(const std::variant<uint, std::wstring>& player); DLL cpp::result<bool, Error> GetReservedSlot(const std::variant<uint, std::wstring>& player); DLL cpp::result<void, Error> SetReservedSlot(const std::variant<uint, std::wstring>& player, bool bReservedSlot); DLL cpp::result<void, Error> ResetRep(const std::variant<uint, std::wstring>& player); DLL cpp::result<std::vector<GroupMember>, Error> GetGroupMembers(const std::variant<uint, std::wstring>& player); DLL cpp::result<void, Error> SetRep(const std::variant<uint, std::wstring>& player, const std::wstring& wscRepGroup, float fValue); DLL cpp::result<float, Error> GetRep(const std::variant<uint, std::wstring>& player, const std::variant<uint, std::wstring>& repGroup); DLL cpp::result<std::list<std::wstring>, Error> ReadCharFile(const std::variant<uint, std::wstring>& player); DLL cpp::result<void, Error> WriteCharFile(const std::variant<uint, std::wstring>& player, std::wstring wscData); DLL cpp::result<void, Error> PlayerRecalculateCRC(ClientId client); DLL std::string GetPlayerSystemS(ClientId client); DLL bool IsInRange(ClientId client, float fDistance); DLL cpp::result<void, Error> SetEquip(const std::variant<uint, std::wstring>& player, const st6::list<EquipDesc>& equip); DLL cpp::result<void, Error> AddEquip(const std::variant<uint, std::wstring>& player, uint iGoodId, const std::string& scHardpoint); DLL cpp::result<void, Error> AntiCheat(ClientId client); DLL void DelayedKick(ClientId client, uint secs); DLL void DeleteCharacter(CAccount* acc, const std::wstring& character); DLL cpp::result<void, Error> NewCharacter(CAccount* acc, std::wstring& character); DLL cpp::result<int, Error> GetOnlineTime(const std::variant<uint, std::wstring>& player); DLL cpp::result<int, Error> GetRank(const std::variant<uint, std::wstring>& player); DLL cpp::result<const uint, Error> GetShipValue(const std::variant<uint, std::wstring>& player); DLL void RelocateClient(ClientId client, Vector vDestination, const Matrix& mOrientation); DLL void SaveChar(ClientId client); DLL cpp::result<const ShipId, Error> GetTarget(const std::variant<uint, std::wstring>& player); DLL cpp::result<ClientId, Error> GetTargetClientID(const std::variant<uint, std::wstring>& player); DLL cpp::result<const BaseId, Error> GetCurrentBase(const std::variant<uint, std::wstring>& player); DLL cpp::result<const SystemId, Error> GetSystem(const std::variant<uint, std::wstring>& player); DLL cpp::result<const ShipId, Error> GetShip(const std::variant<uint, std::wstring>& player); DLL cpp::result<const uint, Error> GetShipID(const std::variant<uint, std::wstring>& player); DLL cpp::result<void, Error> MarkObj(const std::variant<uint, std::wstring>& player, uint objId, int markStatus); DLL cpp::result<int, Error> GetPvpKills(const std::variant<uint, std::wstring>& player); DLL cpp::result<void, Error> SetPvpKills(const std::variant<uint, std::wstring>& player, int killAmount); DLL cpp::result<int, Error> IncrementPvpKills(const std::variant<uint, std::wstring>& player); DLL cpp::result<const uint, Error> GetSystemByNickname(std::variant<std::string, std::wstring> nickname); DLL CShip* CShipFromShipDestroyed(const DWORD** ecx); DLL cpp::result<int, Error> SendBestPath(const std::variant<uint, std::wstring>& player, int iStartSysId, Vector vStartPos, int iTargetSysId, Vector vTargetPos); } // namespace Player namespace Solar { DLL cpp::result<const SystemId, Error> GetSystemBySpaceId(uint spaceObjId); DLL cpp::result<std::pair<Vector, Matrix>, Error> GetLocation(uint id, IdType type); DLL cpp::result<float, Error> GetMass(uint spaceObjId); DLL cpp::result<std::pair<Vector, Vector>, Error> GetMotion(uint spaceObjId); DLL cpp::result<uint, Error> GetType(uint spaceObjId); DLL cpp::result<Universe::IBase*, Error> GetBaseByWildcard(const std::wstring& targetBaseName); DLL cpp::result<uint, Error> GetAffiliation(BaseId solarId); DLL cpp::result<float, Error> GetCommodityPrice(BaseId baseId, GoodId goodId); } // namespace Solar namespace Ini { DLL cpp::result<std::wstring, Error> GetFromPlayerFile(const std::variant<uint, std::wstring>& player, const std::wstring& wscKey); DLL cpp::result<void, Error> WriteToPlayerFile( const std::variant<uint, std::wstring>& player, const std::wstring& wscKey, const std::wstring& wscValue); DLL void SetCharacterIni(ClientId client, const std::wstring& name, std::wstring value); DLL std::wstring GetCharacterIniString(ClientId client, const std::wstring& name); DLL bool GetCharacterIniBool(ClientId client, const std::wstring& name); DLL int GetCharacterIniInt(ClientId client, const std::wstring& name); DLL uint GetCharacterIniUint(ClientId client, const std::wstring& name); DLL float GetCharacterIniFloat(ClientId client, const std::wstring& name); DLL double GetCharacterIniDouble(ClientId client, const std::wstring& name); DLL int64_t GetCharacterIniInt64(ClientId client, const std::wstring& name); } // namespace Ini namespace Admin { DLL std::wstring GetPlayerIP(ClientId client); DLL cpp::result<PlayerInfo, Error> GetPlayerInfo(const std::variant<uint, std::wstring>& player, bool bAlsoCharmenu); DLL std::list<PlayerInfo> GetPlayers(); DLL cpp::result<DPN_CONNECTION_INFO, Error> GetConnectionStats(ClientId client); DLL cpp::result<void, Error> SetAdmin(const std::variant<uint, std::wstring>& player, const std::wstring& wscRights); DLL cpp::result<std::wstring, Error> GetAdmin(const std::variant<uint, std::wstring>& player); DLL cpp::result<void, Error> DelAdmin(const std::variant<uint, std::wstring>& player); DLL cpp::result<void, Error> ChangeNPCSpawn(bool bDisable); DLL cpp::result<BaseHealth, Error> GetBaseStatus(const std::wstring& wscBasename); DLL Fuse* GetFuseFromID(uint iFuseId); DLL bool LightFuse(IObjRW* ship, uint iFuseId, float fDelay, float fLifetime, float fSkip); DLL bool UnLightFuse(IObjRW* ship, uint iFuseId); DLL CEqObj* GetEqObjFromObjRW(struct IObjRW* objRW); } // namespace Admin namespace Err { DLL std::wstring ErrGetText(Error Err); } namespace Personalities { DLL cpp::result<pub::AI::Personality, Error> GetPersonality(const std::string& pilotNickname); } namespace ZoneUtilities { DLL void ReadUniverse(std::multimap<uint, LootableZone, std::less<>>* zones); DLL void ReadLootableZone( std::multimap<uint, LootableZone, std::less<>>& zones, const std::string& systemNick, const std::string& defaultZoneNick, const std::string& file); DLL void ReadSystemLootableZones(std::multimap<uint, LootableZone, std::less<>>& zones, const std::string& systemNick, const std::string& file); DLL void ReadSystemZones(std::multimap<uint, LootableZone, std::less<>>& zones, const std::string& systemNick, const std::string& file); DLL bool InZone(uint systemId, const Vector& pos, Zone& rlz); DLL bool InDeathZone(uint systemId, const Vector& pos, Zone& rlz); DLL SystemInfo* GetSystemInfo(uint systemId); DLL void PrintZones(); } // namespace ZoneUtilities } // namespace Hk
16,745
C++
.h
288
55.09375
163
0.75338
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,470
Utils.hpp
TheStarport_FLHook/include/Tools/Utils.hpp
#pragma once inline HWND GetFLServerHwnd() { const auto* unkThis = (void*)0x00426C58; return *(HWND*)(*((DWORD*)unkThis + 8) + 32); } inline void SwapBytes(void* ptr, uint iLen) { if (iLen % 4) return; for (uint i = 0; i < iLen; i += 4) { char* ptr1 = (char*)ptr + i; unsigned long temp; memcpy(&temp, ptr1, 4); char* ptr2 = (char*)&temp; memcpy(ptr1, ptr2 + 3, 1); memcpy(ptr1 + 1, ptr2 + 2, 1); memcpy(ptr1 + 2, ptr2 + 1, 1); memcpy(ptr1 + 3, ptr2, 1); } } inline void WriteProcMem(void* pAddress, const void* pMem, int iSize) { HANDLE hProc = OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, FALSE, GetCurrentProcessId()); DWORD dwOld; VirtualProtectEx(hProc, pAddress, iSize, PAGE_EXECUTE_READWRITE, &dwOld); WriteProcessMemory(hProc, pAddress, pMem, iSize, 0); CloseHandle(hProc); } inline void ReadProcMem(void* pAddress, void* pMem, int iSize) { HANDLE hProc = OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, FALSE, GetCurrentProcessId()); DWORD dwOld; VirtualProtectEx(hProc, pAddress, iSize, PAGE_EXECUTE_READWRITE, &dwOld); ReadProcessMemory(hProc, pAddress, pMem, iSize, 0); CloseHandle(hProc); } inline int ToInt(const std::wstring& wscStr) { return wcstol(wscStr.c_str(), nullptr, 10); } inline int64 ToInt64(const std::wstring& str) { return str.empty() ? 0 : wcstoll(str.c_str(), nullptr, 10); } inline uint ToUInt(const std::wstring& wscStr) { if (wscStr.find(L"-") != std::wstring::npos) { return 0; } return wcstoul(wscStr.c_str(), nullptr, 10); } //! Converts numeric value with a metric suffix to the full value, eg 10k translates to 10000 inline uint MultiplyUIntBySuffix(const std::wstring& valueString) { uint value = wcstoul(valueString.c_str(), nullptr, 10); const auto lastChar = valueString.back(); if (lastChar == *L"k" || lastChar == *L"K") { return value * 1000; } if (lastChar == *L"m" || lastChar == *L"M") { return value * 1000000; } return value; } inline std::chrono::sys_time<std::chrono::seconds> UnixToSysTime(int64 time) { return std::chrono::sys_time<std::chrono::seconds> {std::chrono::seconds {time}}; } inline std::wstring XMLText(const std::wstring& text) { std::wstring wscRet; for (uint i = 0; (i < text.length()); i++) { if (text[i] == '<') wscRet.append(L"&#60;"); else if (text[i] == '>') wscRet.append(L"&#62;"); else if (text[i] == '&') wscRet.append(L"&#38;"); else wscRet.append(1, text[i]); } return wscRet; } /** Remove leading and trailing spaces from the std::string ~FlakCommon by Motah. */ template<typename Str> Str Trim(const Str& stringInput) requires StringRestriction<Str> { if (stringInput.empty()) return stringInput; using Char = typename Str::value_type; constexpr auto trimmable = []() constexpr { if constexpr (std::is_same_v<Char, char>) return " \t\n\r"; else if constexpr (std::is_same_v<Char, wchar_t>) return L" \t\n\r"; }(); auto start = stringInput.find_first_not_of(trimmable); auto end = stringInput.find_last_not_of(trimmable); if (start == end) return stringInput; return stringInput.substr(start, end - start + 1); } template<typename TString> TString ExpandEnvironmentVariables(const TString& input) { std::string accumulator = ""; std::string output = ""; bool percentFound = false; for (uint i = 0; i < input.length(); i++) { const auto ch = input[i]; if (ch == '%') { if (percentFound || (input[i + 1] != '%')) { percentFound = !percentFound; if (percentFound) accumulator.clear(); else { auto var = std::getenv(accumulator.c_str()); accumulator = var ? var : accumulator; output += accumulator; } } else { i++; // Extra percentage sign, escape it. } } else { if (percentFound) accumulator += ch; else output += ch; } } TString ret = Trim(output); return ret; } template<typename TStr, typename TChar> inline TStr GetParam(const TStr& line, TChar splitChar, uint pos) requires StringRestriction<TStr> { uint i; uint j; TStr result; for (i = 0, j = 0; (i <= pos) && (j < line.length()); j++) { if (line[j] == splitChar) { while (((j + 1) < line.length()) && (line[j + 1] == splitChar)) j++; // skip "whitechar" i++; continue; } if (i == pos) result += line[j]; } return result; } template<typename TString, typename TChar> TString GetParamToEnd(const TString& line, TChar splitChar, uint pos) requires StringRestriction<TString> { for (uint i = 0, j = 0; (i <= pos) && (j < line.length()); j++) { if (line[j] == splitChar) { while (((j + 1) < line.length()) && (line[j + 1] == splitChar)) j++; // skip "whitechar" i++; continue; } if (i == pos) { return line.substr(j); } } return TString(); } template<typename TString> auto Split(const TString& input, const TString& splitCharacter) requires StringRestriction<TString> { auto inputCopy = input; size_t pos = 0; std::vector<TString> tokens; while ((pos = inputCopy.find(splitCharacter)) != TString::npos) { TString token = inputCopy.substr(0, pos); tokens.emplace_back(token); inputCopy.erase(0, pos + splitCharacter.length()); } if (!inputCopy.empty() && inputCopy.size() != input.size()) { tokens.emplace_back(inputCopy); } return tokens; } template<typename TString, typename TChar> auto Split(const TString& input, const TChar& splitCharacter) requires StringRestriction<TString> { return Split(input, TString(1, splitCharacter)); } template<typename TString, typename TTStr, typename TTTStr> TString ReplaceStr(const TString& source, const TTStr& searchForRaw, const TTTStr& replaceWithRaw) requires StringRestriction<TString> { const TString searchFor = searchForRaw; const TString replaceWith = replaceWithRaw; uint lPos, sPos = 0; TString result = source; while ((lPos = static_cast<uint>(result.find(searchFor, sPos))) != UINT_MAX) { result.replace(lPos, searchFor.length(), replaceWith); sPos = lPos + replaceWith.length(); } return result; } template<typename T> std::wstring ToMoneyStr(T cash) { std::wstringstream ss; ss.imbue(std::locale("")); ss << std::fixed << cash; return ss.str(); } inline float ToFloat(const std::wstring& string) { return wcstof(string.c_str(), nullptr); } inline FARPROC PatchCallAddr(char* mod, DWORD installAddress, const char* hookFunction) { DWORD dwRelAddr; ReadProcMem(mod + installAddress + 1, &dwRelAddr, 4); DWORD dwOffset = (DWORD)hookFunction - (DWORD)(mod + installAddress + 5); WriteProcMem(mod + installAddress + 1, &dwOffset, 4); return (FARPROC)(mod + dwRelAddr + installAddress + 5); } inline std::wstring ToLower(std::wstring string) { std::transform(string.begin(), string.end(), string.begin(), towlower); return string; } inline std::string ToLower(std::string string) { std::transform(string.begin(), string.end(), string.begin(), tolower); return string; } inline std::wstring ViewToWString(const std::wstring& wstring) { return {wstring.begin(), wstring.end()}; } inline std::string ViewToString(const std::string_view& stringView) { return {stringView.begin(), stringView.end()}; } inline std::wstring stows(const std::string& text) { int size = MultiByteToWideChar(CP_ACP, 0, text.c_str(), -1, 0, 0); auto wideText = new wchar_t[size]; MultiByteToWideChar(CP_ACP, 0, text.c_str(), -1, wideText, size); std::wstring wscRet = wideText; delete[] wideText; return wscRet; } inline std::string wstos(const std::wstring& text) { uint iLen = (uint)text.length() + 1; auto szBuf = new char[iLen]; WideCharToMultiByte(CP_ACP, 0, text.c_str(), -1, szBuf, iLen, 0, 0); std::string scRet = szBuf; delete[] szBuf; return scRet; } template<typename TStr> auto strswa(TStr str) requires StringRestriction<TStr> { if constexpr (std::is_same_v<TStr, std::string>) { return stows(str); } else { return wstos(str); } }
7,953
C++
.h
300
24.16
117
0.694835
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,471
Enums.hpp
TheStarport_FLHook/include/Tools/Enums.hpp
#pragma once enum class LogLevel : int { Trace, Debug, Info, Warn, Err, Critical }; enum class LogType : int { Normal, Cheater, Kick, Connects, AdminCmds, UserLogCmds, SocketCmds, PerfTimers }; enum class Error { NicknameNotFound, PlayerNotInSpace, PlayerNotLoggedIn, PlayerNotDocked, CharacterNotSelected, CharacterDoesNotExist, CannotGetAccount, MpNewCharacterFileNotFoundOrInvalid, NoTargetSelected, TargetIsNotPlayer, CouldNotDecodeCharFile, CouldNotEncodeCharFile, NoAdmin, WrongXmlSyntax, InvalidClientId, InvalidGood, InvalidShip, InvalidBase, InvalidBaseName, InvalidIdString, InvalidSystem, InvalidRepGroup, InvalidGroupId, AlreadyExists, CharacterNameTooLong, CharacterNameTooShort, AmbiguousShortcut, NoMatchingPlayer, InvalidShortcutString, PluginCannotBeLoaded, PluginNotFound, InvalidIdType, InvalidSpaceObjId, UnknownError = 1000, }; enum DIEMSGTYPE { DIEMSG_ALL = 0, DIEMSG_SYSTEM = 1, DIEMSG_NONE = 2, DIEMSG_SELF = 3, }; enum CHATSIZE { CS_DEFAULT = 0, CS_SMALL = 1, CS_BIG = 2, }; enum CHATSTYLE { CST_DEFAULT = 0, CST_BOLD = 1, CST_ITALIC = 2, CST_UNDERLINE = 3, }; enum EngineState { ES_CRUISE, ES_THRUSTER, ES_ENGINE, ES_KILLED, ES_TRADELANE }; enum EquipmentType { ET_GUN, ET_TORPEDO, ET_CD, ET_MISSILE, ET_MINE, ET_CM, ET_SHIELDGEN, ET_THRUSTER, ET_SHIELDBAT, ET_NANOBOT, ET_MUNITION, ET_ENGINE, ET_OTHER, ET_SCANNER, ET_TRACTOR, ET_LIGHT }; enum CCMDS_RIGHTS { RIGHT_NOTHING = 0, RIGHT_SUPERADMIN = 0xFFFFFFFF, RIGHT_MSG = (1 << 0), RIGHT_KICKBAN = (1 << 1), RIGHT_EVENTMODE = (1 << 2), RIGHT_CASH = (1 << 3), RIGHT_BEAMKILL = (1 << 4), RIGHT_REPUTATION = (1 << 5), RIGHT_CARGO = (1 << 6), RIGHT_CHARACTERS = (1 << 7), RIGHT_SETTINGS = (1 << 8), RIGHT_PLUGINS = (1 << 9), RIGHT_OTHER = (1 << 10), RIGHT_SPECIAL1 = (1 << 11), RIGHT_SPECIAL2 = (1 << 12), RIGHT_SPECIAL3 = (1 << 13), }; enum class PluginMajorVersion { UNDEFINED = -1, // We started doing this from 4 onwards VERSION_04 = 4, }; // Define most ahead of time enum class PluginMinorVersion { UNDEFINED = -1, VERSION_00 = 0, VERSION_01, VERSION_02, VERSION_03, VERSION_04, VERSION_05, VERSION_06, VERSION_07, VERSION_08, VERSION_09, }; enum class ReturnCode { Default = 0, SkipPlugins = 1, SkipFunctionCall = 2, SkipAll = SkipPlugins | SkipFunctionCall, }; inline ReturnCode operator&(ReturnCode a, ReturnCode b) { return ReturnCode(static_cast<uint>(a) & static_cast<uint>(b)); } enum class HookStep { Before, After }; enum class HookedCall { IEngine__CShip__Init, IEngine__CShip__Destroy, IEngine__UpdateTime, IEngine__ElapseTime, IEngine__DockCall, IEngine__LaunchPosition, IEngine__ShipDestroyed, IEngine__BaseDestroyed, IEngine__GuidedHit, IEngine__AddDamageEntry, IEngine__DamageHit, IEngine__AllowPlayerDamage, IEngine__SendDeathMessage, FLHook__TimerCheckKick, FLHook__TimerNPCAndF1Check, FLHook__UserCommand__Process, FLHook__AdminCommand__Help, FLHook__AdminCommand__Process, FLHook__LoadSettings, FLHook__LoadCharacterSettings, FLHook__ClearClientInfo, FLHook__ProcessEvent, IChat__SendChat, IClientImpl__Send_FLPACKET_COMMON_FIREWEAPON, IClientImpl__Send_FLPACKET_COMMON_ACTIVATEEQUIP, IClientImpl__Send_FLPACKET_COMMON_ACTIVATECRUISE, IClientImpl__Send_FLPACKET_COMMON_ACTIVATETHRUSTERS, IClientImpl__CDPClientProxy__GetLinkSaturation, IClientImpl__Send_FLPACKET_SERVER_SETSHIPARCH, IClientImpl__Send_FLPACKET_SERVER_SETHULLSTATUS, IClientImpl__Send_FLPACKET_SERVER_SETCOLLISIONGROUPS, IClientImpl__Send_FLPACKET_SERVER_SETEQUIPMENT, IClientImpl__Send_FLPACKET_SERVER_SETADDITEM, IClientImpl__Send_FLPACKET_SERVER_SETSTARTROOM, IClientImpl__Send_FLPACKET_SERVER_CREATESOLAR, IClientImpl__Send_FLPACKET_SERVER_CREATESHIP, IClientImpl__Send_FLPACKET_SERVER_CREATELOOT, IClientImpl__Send_FLPACKET_SERVER_CREATEMINE, IClientImpl__Send_FLPACKET_SERVER_CREATEGUIDED, IClientImpl__Send_FLPACKET_SERVER_CREATECOUNTER, IClientImpl__Send_FLPACKET_COMMON_UPDATEOBJECT, IClientImpl__Send_FLPACKET_SERVER_DESTROYOBJECT, IClientImpl__Send_FLPACKET_SERVER_ACTIVATEOBJECT, IClientImpl__Send_FLPACKET_SERVER_LAUNCH, IClientImpl__Send_FLPACKET_SERVER_REQUESTCREATESHIPRESP, IClientImpl__Send_FLPACKET_SERVER_USE_ITEM, IClientImpl__Send_FLPACKET_SERVER_SETREPUTATION, IClientImpl__Send_FLPACKET_SERVER_SENDCOMM, IClientImpl__Send_FLPACKET_SERVER_SET_MISSION_MESSAGE, IClientImpl__Send_FLPACKET_SERVER_SETMISSIONOBJECTIVES, IClientImpl__Send_FLPACKET_SERVER_SETCASH, IClientImpl__Send_FLPACKET_SERVER_BURNFUSE, IClientImpl__Send_FLPACKET_SERVER_SCANNOTIFY, IClientImpl__Send_FLPACKET_SERVER_PLAYERLIST, IClientImpl__Send_FLPACKET_SERVER_PLAYERLIST_2, IClientImpl__Send_FLPACKET_SERVER_MISCOBJUPDATE_6, IClientImpl__Send_FLPACKET_SERVER_MISCOBJUPDATE_7, IClientImpl__Send_FLPACKET_SERVER_MISCOBJUPDATE, IClientImpl__Send_FLPACKET_SERVER_MISCOBJUPDATE_2, IClientImpl__Send_FLPACKET_SERVER_MISCOBJUPDATE_3, IClientImpl__Send_FLPACKET_SERVER_MISCOBJUPDATE_4, IClientImpl__Send_FLPACKET_SERVER_MISCOBJUPDATE_5, IServerImpl__FireWeapon, IServerImpl__ActivateEquip, IServerImpl__ActivateCruise, IServerImpl__ActivateThrusters, IServerImpl__SetTarget, IServerImpl__TractorObjects, IServerImpl__GoTradelane, IServerImpl__StopTradelane, IServerImpl__JettisonCargo, IServerImpl__Startup, IServerImpl__Shutdown, IServerImpl__Update, IServerImpl__DisConnect, IServerImpl__OnConnect, IServerImpl__Login, IServerImpl__CharacterInfoReq, IServerImpl__CharacterSelect, IServerImpl__CreateNewCharacter, IServerImpl__DestroyCharacter, IServerImpl__ReqShipArch, IServerImpl__ReqHullStatus, IServerImpl__ReqCollisionGroups, IServerImpl__ReqEquipment, IServerImpl__ReqAddItem, IServerImpl__ReqRemoveItem, IServerImpl__ReqModifyItem, IServerImpl__ReqSetCash, IServerImpl__ReqChangeCash, IServerImpl__BaseEnter, IServerImpl__BaseExit, IServerImpl__LocationEnter, IServerImpl__LocationExit, IServerImpl__BaseInfoRequest, IServerImpl__LocationInfoRequest, IServerImpl__GFObjSelect, IServerImpl__GFGoodVaporized, IServerImpl__MissionResponse, IServerImpl__TradeResponse, IServerImpl__GFGoodBuy, IServerImpl__GFGoodSell, IServerImpl__SystemSwitchOutComplete, IServerImpl__PlayerLaunch, IServerImpl__LaunchComplete, IServerImpl__JumpInComplete, IServerImpl__Hail, IServerImpl__SPObjUpdate, IServerImpl__SPMunitionCollision, IServerImpl__SPObjCollision, IServerImpl__SPRequestUseItem, IServerImpl__SPRequestInvincibility, IServerImpl__RequestEvent, IServerImpl__RequestCancel, IServerImpl__MineAsteroid, IServerImpl__RequestCreateShip, IServerImpl__SPScanCargo, IServerImpl__SetManeuver, IServerImpl__InterfaceItemUsed, IServerImpl__AbortMission, IServerImpl__SetWeaponGroup, IServerImpl__SetVisitedState, IServerImpl__RequestBestPath, IServerImpl__RequestPlayerStats, IServerImpl__PopupDialog, IServerImpl__RequestGroupPositions, IServerImpl__SetInterfaceState, IServerImpl__RequestRankLevel, IServerImpl__InitiateTrade, IServerImpl__TerminateTrade, IServerImpl__AcceptTrade, IServerImpl__SetTradeMoney, IServerImpl__AddTradeEquip, IServerImpl__DelTradeEquip, IServerImpl__RequestTrade, IServerImpl__StopTradeRequest, IServerImpl__SubmitChat, Count }; enum class MessageColor { AliceBlue = 0xF0F8FF, AntiqueWhite = 0xFAEBD7, Aqua = 0x00FFFF, Aquamarine = 0x7FFFD4, Azure = 0xF0FFFF, Beige = 0xF5F5DC, Bisque = 0xFFE4C4, Black = 0x000000, BlanchedAlmond = 0xFFEBCD, Blue = 0x0000FF, BlueViolet = 0x8A2BE2, Brown = 0xA52A2A, BurlyWood = 0xDEB887, CadetBlue = 0x5F9EA0, Chartreuse = 0x7FFF00, Chocolate = 0xD2691E, Coral = 0xFF7F50, CornflowerBlue = 0x6495ED, Cornsilk = 0xFFF8DC, Crimson = 0xDC143C, Cyan = 0x00FFFF, DarkBlue = 0x00008B, DarkCyan = 0x008B8B, DarkGoldenrod = 0xB8860B, DarkGray = 0xA9A9A9, DarkGreen = 0x006400, DarkKhaki = 0xBDB76B, DarkMagenta = 0x8B008B, DarkOliveGreen = 0x556B2F, DarkOrange = 0xFF8C00, DarkOrchid = 0x9932CC, DarkRed = 0x8B0000, DarkSalmon = 0xE9967A, DarkSeaGreen = 0x8FBC8F, DarkSlateBlue = 0x483D8B, DarkSlateGray = 0x2F4F4F, DarkTurquoise = 0x00CED1, DarkViolet = 0x9400D3, DeepPink = 0xFF1493, DeepSkyBlue = 0x00BFFF, DimGray = 0x696969, DodgerBlue = 0x1E90FF, Firebrick = 0xB22222, FloralWhite = 0xFFFAF0, ForestGreen = 0x228B22, Fuchsia = 0xFF00FF, Gainsboro = 0xDCDCDC, GhostWhite = 0xF8F8FF, Gold = 0xFFD700, Goldenrod = 0xDAA520, Gray = 0x808080, Green = 0x008000, GreenYellow = 0xADFF2F, Honeydew = 0xF0FFF0, HotPink = 0xFF69B4, IndianRed = 0xCD5C5C, Indigo = 0x4B0082, Ivory = 0xFFFFF0, Khaki = 0xF0E68C, Lavender = 0xE6E6FA, LavenderBlush = 0xFFF0F5, LawnGreen = 0x7CFC00, LemonChiffon = 0xFFFACD, LightBlue = 0xADD8E6, LightCoral = 0xF08080, LightCyan = 0xE0FFFF, LightGoldenrodYellow = 0xFAFAD2, LightGray = 0xD3D3D3, LightGreen = 0x90EE90, LightPink = 0xFFB6C1, LightSalmon = 0xFFA07A, LightSeaGreen = 0x20B2AA, LightSkyBlue = 0x87CEFA, LightSlateGray = 0x778899, LightSteelBlue = 0xB0C4DE, LightYellow = 0xFFFFE0, Lime = 0x00FF00, LimeGreen = 0x32CD32, Linen = 0xFAF0E6, Magenta = 0xFF00FF, Maroon = 0x800000, MediumAquamarine = 0x66CDAA, MediumBlue = 0x0000CD, MediumOrchid = 0xBA55D3, MediumPurple = 0x9370DB, MediumSeaGreen = 0x3CB371, MediumSlateBlue = 0x7B68EE, MediumSpringGreen = 0x00FA9A, MediumTurquoise = 0x48D1CC, MediumVioletRed = 0xC71585, MidnightBlue = 0x191970, MintCream = 0xF5FFFA, MistyRose = 0xFFE4E1, Moccasin = 0xFFE4B5, NavajoWhite = 0xFFDEAD, Navy = 0x000080, OldLace = 0xFDF5E6, Olive = 0x808000, OliveDrab = 0x6B8E23, Orange = 0xFFA500, OrangeRed = 0xFF4500, Orchid = 0xDA70D6, PaleGoldenrod = 0xEEE8AA, PaleGreen = 0x98FB98, PaleTurquoise = 0xAFEEEE, PaleVioletRed = 0xDB7093, PapayaWhip = 0xFFEFD5, PeachPuff = 0xFFDAB9, Peru = 0xCD853F, Pink = 0xFFC0CB, Plum = 0xDDA0DD, PowderBlue = 0xB0E0E6, Purple = 0x800080, Red = 0xFF0000, RosyBrown = 0xBC8F8F, RoyalBlue = 0x4169E1, SaddleBrown = 0x8B4513, Salmon = 0xFA8072, SandyBrown = 0xF4A460, SeaGreen = 0x2E8B57, SeaShell = 0xFFF5EE, Sienna = 0xA0522D, Silver = 0xC0C0C0, SkyBlue = 0x87CEEB, SlateBlue = 0x6A5ACD, SlateGray = 0x708090, Snow = 0xFFFAFA, SpringGreen = 0x00FF7F, SteelBlue = 0x4682B4, Tan = 0xD2B48C, Teal = 0x008080, Thistle = 0xD8BFD8, Tomato = 0xFF6347, Turquoise = 0x40E0D0, Violet = 0xEE82EE, Wheat = 0xF5DEB3, White = 0xFFFFFF, WhiteSmoke = 0xF5F5F5, Yellow = 0xFFFF00, YellowGreen = 0x9ACD32, }; enum class MessageFormat { Normal = 0x0, Bold = 0x1, Italic = 0x2, Underline = 0x4, Big = 0x8, BigAndWide = 0x10, VeryBig = 0x20, Smoothest = 0x40, Smoother = 0x80, Small = 0x90, BoldAndItalic = Bold | Italic, BoldAndItalicAndUnderline = Bold | Italic | Underline, BoldAndUnderline = Bold | Underline, ItalicAndUnderline = Italic | Underline, BigAndBold = Big | Bold, }; enum class IdType { Client, Ship = 1, Solar = 1, Equip, Arch, Reputation };
10,974
C++
.h
472
21.330508
64
0.798741
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,472
Typedefs.hpp
TheStarport_FLHook/include/Tools/Typedefs.hpp
#pragma once #include <string> using uint = unsigned int; using uchar = unsigned char; using ushort = unsigned short; using ulong = unsigned long; using int64 = long long; using uint64 = unsigned long long; using mstime = uint64; // Common types that can be used to explain what is being used using ClientId = const uint; using SystemId = const uint; using ShipId = const uint; using EquipId = const uint; using BaseId = const uint; using RepId = const ushort; using GoodId = const uint; using ArchId = const uint; using st6_malloc_t = void* (*)(size_t); using st6_free_t = void (*)(void*); using _RCSendChatMsg = void(__stdcall*)(uint iId, uint iTo, uint iSize, void* pRDL); using _CRCAntiCheat = void(__stdcall*)(); using _GetFLName = int(__cdecl*)(char* szBuf, const wchar_t* wszStr); using _GetShipInspect = bool(__cdecl*)(uint& ship, class IObjInspectImpl*& inspect, uint& iDunno); using BLOWFISH_CTX = struct { unsigned long P[16 + 2]; unsigned long S[4][256]; }; using BYTE = unsigned char; using UserCmdProc = void(*)(ClientId& client); using UserCmdProcWithParam = void(*)(ClientId& client, const std::wstring& param);
1,139
C++
.h
32
34.25
98
0.741348
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,473
Macros.hpp
TheStarport_FLHook/include/Tools/Macros.hpp
#pragma once #ifndef DLL #ifndef FLHOOK #define DLL __declspec(dllimport) #else #define DLL __declspec(dllexport) #endif #endif #ifndef FLHOOK #define EXTERN extern #else #define EXTERN #endif #define SRV_ADDR(a) ((char*)hModServer + (a)) #define DALIB_ADDR(a) ((char*)hModDaLib + (a)) #define FLSERVER_ADDR(a) ((char*)hProcFL + (a)) #define CONTENT_ADDR(a) ((char*)hModContent + (a)) #ifndef DISABLE_EXTENDED_EXCEPTION_LOGGING #pragma warning(disable : 4091) #include <DbgHelp.h> struct SEHException { SEHException(uint code, EXCEPTION_POINTERS* ep) : code(code), record(*ep->ExceptionRecord), context(*ep->ContextRecord) {} SEHException() = default; uint code; EXCEPTION_RECORD record; CONTEXT context; static void Translator(uint code, EXCEPTION_POINTERS* ep) { throw SEHException(code, ep); } }; DLL void WriteMiniDump(SEHException* ex); DLL void AddExceptionInfoLog(); DLL void AddExceptionInfoLog(SEHException* ex); #define TRY_HOOK \ try \ { \ _set_se_translator(SEHException::Translator); #define CATCH_HOOK(e) \ } \ catch (SEHException & ex) \ { \ e; \ AddLog(LogType::Normal, LogLevel::Err, std::format("ERROR: SEH Exception in {} on line {}; minidump may contain more information.", __FUNCTION__, __LINE__)); \ AddExceptionInfoLog(&ex); \ } \ catch (std::exception & ex) \ { \ e; \ AddLog(LogType::Normal, LogLevel::Err, std::format("ERROR: STL Exception in {} on line {}: {}.", __FUNCTION__, __LINE__, ex.what())); \ AddExceptionInfoLog(0); \ } \ catch (...) \ { \ e; \ AddLog(LogType::Normal, LogLevel::Err, std::format("ERROR: Exception in {} on line {}.", __FUNCTION__, __LINE__)); \ AddExceptionInfoLog(0); \ } #define LOG_EXCEPTION \ { \ AddLog(LogType::Normal, LogLevel::Err, std::format("ERROR Exception in {}", __FUNCTION__)); \ AddExceptionInfoLog(); \ } #else #define TRY_HOOK try #define CATCH_HOOK(e) \ catch (...) \ { \ e; \ AddLog(LogType::Normal, LogLevel::Err, std::format("ERROR: Exception in {}", __FUNCTION__)); \ } #endif #define GetPluginClientData(id, info) ((&ClientInfo[(id)])->mapPluginData[(info)].data()) #define DefaultDllMain(x) \ BOOL WINAPI DllMain([[maybe_unused]] HINSTANCE dll, [[maybe_unused]] DWORD reason, [[maybe_unused]] LPVOID reserved) \ { \ if (CoreGlobals::c()->flhookReady && reason == DLL_PROCESS_ATTACH) \ { \ x; \ } \ return true; \ } #define DefaultDllMainSettings(loadSettings) DefaultDllMain(loadSettings())
5,725
C++
.h
81
68.160494
162
0.290431
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,474
Deps.hpp
TheStarport_FLHook/include/Tools/Deps.hpp
#pragma once #ifdef SERVER #include <ext/Sql.hpp> #pragma warning(push, 0) #include <ext/jpcre2.hpp> #pragma warning(pop) using jp = jpcre2::select<char>; using jpWide = jpcre2::select<wchar_t>; #include <ext/result.hpp> #include <ext/Wildcard.hpp> #include "magic_enum.hpp" #pragma comment(lib, "pcre2-8.lib") #pragma comment(lib, "pcre2-16.lib") #pragma comment(lib, "pcre2-32.lib") #pragma comment(lib, "pcre2-posix.lib") #else #ifdef FMT #include "fmt/core.h" #include "fmt/format.h" #include "fmt/xchar.h" #endif #ifdef SQL #include <ext/Sql.hpp> #endif #ifdef PCRE2 #pragma warning(push, 0) #include <ext/jpcre2.hpp> #pragma warning(pop) using jp = jpcre2::select<char>; using jpWide = jpcre2::select<wchar_t>; #pragma comment(lib, "pcre2-8.lib") #pragma comment(lib, "pcre2-16.lib") #pragma comment(lib, "pcre2-32.lib") #pragma comment(lib, "pcre2-posix.lib") #endif #ifdef RESULT #include <ext/result.hpp> #endif #ifdef WILDCARD #include <ext/Wildcard.hpp> #endif #ifdef ENUM #include "magic_enum.hpp" #endif #ifdef JSON #include <nlohmann/json.hpp> #endif #ifdef REFL #include "refl.hpp" #endif #endif
1,179
C++
.h
51
20.784314
41
0.717605
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,475
Constexpr.hpp
TheStarport_FLHook/include/Tools/Constexpr.hpp
#pragma once constexpr int TimeUpdate = 50; constexpr int MaxClientId = 249;
77
C++
.h
3
24.666667
32
0.810811
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,476
Serializer.hpp
TheStarport_FLHook/include/Tools/Serialization/Serializer.hpp
#ifndef SERIALIZE #define SERIALIZE #include <fstream> #include <nlohmann/json.hpp> #include "refl.hpp" template<typename T> constexpr auto IsEnum = std::is_enum_v<T>; template<typename T> constexpr auto IsBool = std::is_same_v<T, bool>; template<typename T> constexpr auto IsInt = std::is_same_v<T, int> || std::is_same_v<T, uint> || IsEnum<T>; template<typename T> constexpr auto IsBigInt = std::is_same_v<T, long long> || std::is_same_v<T, unsigned long long>; template<typename T> constexpr auto IsFloat = std::is_same_v<T, float>; template<typename T> constexpr auto IsString = std::is_same_v<T, std::string>; template<typename T> constexpr auto IsWString = std::is_same_v<T, std::wstring>; template<typename T> constexpr auto IsReflectable = std::is_base_of_v<Reflectable, T>; template<typename T> constexpr auto IsAnyValidType = IsBool<T> || IsInt<T> || IsBigInt<T> || IsFloat<T> || IsString<T> || IsWString<T> || IsReflectable<T>; template<typename> struct IsVector : std::false_type { }; template<typename T, typename A> struct IsVector<std::vector<T, A>> : std::true_type { }; template<typename T, typename TT> constexpr auto IsVectorOfType = std::is_same_v<T, std::vector<TT>>; template<typename> struct IsMap : std::false_type { }; template<typename T, typename A> struct IsMap<std::map<T, A>> : std::true_type { }; template<typename T, typename TT, typename TTT> constexpr auto IsMapOfType = std::is_same_v<T, std::map<TT, TTT>>; class Serializer { template<typename DeclType, typename Json = nlohmann::json, typename Member, typename ReturnVector = std::vector<typename DeclType::value_type>> static ReturnVector ReadVector(Json json, Member member) { if constexpr (IsBool<typename DeclType::value_type> || IsInt<typename DeclType::value_type> || IsBigInt<typename DeclType::value_type> || IsFloat<typename DeclType::value_type> || IsString<typename DeclType::value_type>) { if (json.is_array()) { return json.get<std::vector<typename DeclType::value_type>>(); } return json[member.name.c_str()].template get<std::vector<typename DeclType::value_type>>(); } else if constexpr (IsWString<typename DeclType::value_type>) { std::vector<std::string> vectorOfString = json.is_array() ? json.get<std::vector<std::string>>() : json[member.name.c_str()].template get<std::vector<std::string>>(); std::vector<std::wstring> vectorOfWstring; for (auto& i : vectorOfString) { vectorOfWstring.emplace_back(stows(i)); } return vectorOfWstring; } else if constexpr (IsReflectable<typename DeclType::value_type>) { auto jArr = json.is_array() ? json.get<nlohmann::json::array_t>() : json[member.name.c_str()].template get<nlohmann::json::array_t>(); auto declArr = std::vector<typename DeclType::value_type>(); for (auto iter = jArr.begin(); iter != jArr.end(); ++iter) { typename DeclType::value_type reflectable; ReadObject(*iter, reflectable); declArr.emplace_back(reflectable); } return declArr; } else { AssertPropertyIsReflectable(member.name.str().c_str(), typeid(DeclType::value_type).name()); } } template<typename StrType, typename Target, typename Json, typename Ptr, typename Member> static void ReadMap(Json json, Ptr ptr, Member member) { if constexpr (IsReflectable<Target>) { nlohmann::json::object_t jObj = json[member.name.c_str()].template get<nlohmann::json::object_t>(); if constexpr (IsWString<StrType>) { auto declMap = std::map<std::wstring, Target>(); for (auto& i : jObj) { Target reflectable; ReadObject(i.second, reflectable); declMap[stows(i.first)] = reflectable; } *static_cast<std::map<std::wstring, Target>*>(ptr) = declMap; } else { auto declMap = std::map<std::string, Target>(); for (auto& i : jObj) { Target reflectable; ReadObject(i.second, reflectable); declMap[i.first] = reflectable; } *static_cast<std::map<std::string, Target>*>(ptr) = declMap; } } else if constexpr (IsVector<Target>::value) { nlohmann::json::object_t jObj = json[member.name.c_str()].template get<nlohmann::json::object_t>(); if constexpr (IsWString<StrType>) { auto declMap = std::map<std::wstring, Target>(); for (auto& i : jObj) { declMap[stows(i.first)] = ReadVector<Target>(json, member); } *static_cast<std::map<std::wstring, Target>*>(ptr) = declMap; } else { auto declMap = std::map<std::string, Target>(); for (auto& i : jObj) { declMap[i.first] = ReadVector<Target>(i.second, member); } *static_cast<std::map<std::string, Target>*>(ptr) = declMap; } } else if constexpr (IsWString<Target>) { std::map<std::string, std::string> mapOfString = json[member.name.c_str()].template get<std::map<std::string, std::string>>(); if constexpr (IsWString<StrType>) { std::map<std::wstring, std::wstring> mapOfWstring; for (const auto& i : mapOfString) { mapOfWstring[stows(i.first)] = stows(i.second); } *static_cast<std::map<std::wstring, std::wstring>*>(ptr) = mapOfWstring; } else { std::map<std::string, std::wstring> mapOfWstring; for (const auto& i : mapOfString) { mapOfWstring[i.first] = stows(i.second); } *static_cast<std::map<std::string, std::wstring>*>(ptr) = mapOfWstring; } } // The next two handle all primitive types else if constexpr (IsString<StrType>) { *static_cast<std::map<std::string, Target>*>(ptr) = json[member.name.c_str()].template get<std::map<std::string, Target>>(); } else if constexpr (IsWString<StrType>) { std::map<std::string, Target> sMap = json[member.name.c_str()].template get<std::map<std::string, Target>>(); std::map<std::wstring, Target> wMap; for (const auto& [key, value] : sMap) wMap[stows(key)] = value; *static_cast<std::map<std::wstring, Target>*>(ptr) = wMap; } else { static_assert(IsString<StrType>, "Non string passed into HandleMapKey"); } } template<typename DeclType, typename Json, typename Ptr, typename Member> static void ReadType(Json json, Ptr ptr, Member member) { if constexpr (IsBool<DeclType>) { *static_cast<bool*>(ptr) = json[member.name.c_str()].template get<bool>(); } else if constexpr (IsInt<DeclType>) { *static_cast<int*>(ptr) = json[member.name.c_str()].template get<int>(); } else if constexpr (IsBigInt<DeclType>) { *static_cast<long long*>(ptr) = json[member.name.c_str()].template get<long long>(); } else if constexpr (IsFloat<DeclType>) { *static_cast<float*>(ptr) = json[member.name.c_str()].template get<float>(); } else if constexpr (IsString<DeclType>) { *static_cast<std::string*>(ptr) = json[member.name.c_str()].template get<std::string>(); } else if constexpr (IsWString<DeclType>) { *static_cast<std::wstring*>(ptr) = stows(json[member.name.c_str()].template get<std::string>()); } else if constexpr (IsReflectable<DeclType>) { nlohmann::json jObj = json[member.name.c_str()].template get<nlohmann::json::object_t>(); DeclType reflectable; ReadObject(jObj, reflectable); *static_cast<DeclType*>(ptr) = reflectable; } else if constexpr (IsVector<DeclType>::value) { *static_cast<std::vector<typename DeclType::value_type>*>(ptr) = ReadVector<DeclType>(json, member); } else if constexpr (IsMap<DeclType>::value) { ReadMap<DeclType>(json, ptr, member); } } template<typename T> static void ReadObject(nlohmann::json& json, T& obj) { constexpr auto type = refl::reflect<T>(); refl::util::for_each(type.members, [&type, &obj, &json](auto member) { // We ignore static and constant values. // Not going to report this as there are use cases where you might want to store constant/static data with // the regular if (member.is_static || !member.is_writable) return; // Get our type with the reference removed typedef std::remove_reference_t<decltype(member(obj))> DeclType; void* ptr = PVOID(std::addressof(obj.*member.pointer)); // Key if our json key exists. If it doesn't we don't care. if (!json.contains(member.name.c_str())) { // Not found return; } if constexpr (IsAnyValidType<DeclType>) { ReadType<DeclType>(json, ptr, member); } else if constexpr (IsVector<DeclType>::value) { *static_cast<std::vector<typename DeclType::value_type>*>(ptr) = ReadVector<DeclType>(json, member); } else if constexpr (IsMap<DeclType>::value) { typedef std::remove_const<DeclType::value_type::first_type>::type MapType; if constexpr (IsWString<MapType> || IsString<MapType>) { ReadMap<MapType, DeclType::value_type::second_type>(json, ptr, member); } else { static_assert(!IsWString<MapType> && !IsString<MapType>, "Key in reflectable map is not a string or wide string."); } } else { static_assert(!IsMap<DeclType>::value, "Non-reflectable property present on reflectable object."); } }); } template<typename T> static void WriteObject(nlohmann::json& json, T& obj) { constexpr auto type = refl::reflect<T>(); refl::util::for_each(type.members, [&type, &obj, &json](auto member) { // We ignore static and constant values. // Not going to report this as there are use cases where you might want to store constant/static data with // the regular if (member.is_static || !member.is_writable) return; // Get our type with the reference removed typedef std::remove_reference_t<decltype(member(obj))> DeclType; if constexpr (IsBool<DeclType> || IsInt<DeclType> || IsFloat<DeclType> || IsString<DeclType> || IsWString<DeclType> || IsBigInt<DeclType>) { if constexpr (IsWString<DeclType>) { json[member.name.c_str()] = wstos(member(obj)); } else { json[member.name.c_str()] = member(obj); } } else if constexpr (IsReflectable<DeclType>) { auto reflectableJson = nlohmann::json::object(); WriteObject(reflectableJson, member(obj)); json[member.name.c_str()] = reflectableJson; } else if constexpr (IsVector<DeclType>::value) { if constexpr (IsBool<typename DeclType::value_type> || IsInt<typename DeclType::value_type> || IsFloat<typename DeclType::value_type> || IsString<typename DeclType::value_type> || IsWString<typename DeclType::value_type> || IsBigInt<typename DeclType::value_type>) { if constexpr (IsWString<typename DeclType::value_type>) { std::vector<std::string> vectorOfStrings; for (std::wstring& i : member(obj)) { vectorOfStrings.emplace_back(wstos(i)); } json[member.name.c_str()] = vectorOfStrings; } else { json[member.name.c_str()] = member(obj); } } else if constexpr (IsReflectable<typename DeclType::value_type>) { std::vector<nlohmann::json::object_t> objects; auto arr = member(obj); for (auto& i : arr) { auto newObj = nlohmann::json::object(); WriteObject(newObj, i); objects.emplace_back(newObj); } json[member.name.c_str()] = objects; } else { static_assert(IsReflectable<typename DeclType::value_type>, "Non-reflectable property present on reflectable object."); } } else if constexpr (IsMap<DeclType>::value) { constexpr bool IsWide = std::is_same_v<class std::basic_string<wchar_t, struct std::char_traits<wchar_t>, class std::allocator<wchar_t>> const, DeclType::value_type::first_type>; constexpr bool IsNotWide = std::is_same_v<class std::basic_string<char, struct std::char_traits<char>, class std::allocator<char>> const, DeclType::value_type::first_type>; static_assert(IsWide || IsNotWide, "Non-reflectable property present on reflectable object."); if constexpr (IsReflectable<typename DeclType::value_type::second_type>) { auto map = member(obj); std::map<std::string, nlohmann::json::object_t> objects; for (auto& i : map) { auto newObj = nlohmann::json::object(); WriteObject(newObj, i.second); if constexpr (IsWide) { objects[wstos(i.first)] = newObj; } else { objects[i.first] = newObj; } } json[member.name.c_str()] = objects; } else { if constexpr (IsWide) { std::map<std::string, typename DeclType::value_type::second_type> map; for (const auto& [key, value] : member(obj)) { map[wstos(key)] = value; } json[member.name.c_str()] = map; } else { json[member.name.c_str()] = member(obj); } } } else { static_assert(!IsMap<DeclType>::value, "Non-reflectable property present on reflectable object."); } }); } template<std::size_t I = 0, typename FuncT, typename... Tp> static typename std::enable_if<I == sizeof...(Tp), void>::type for_each(std::tuple<Tp...>, FuncT) // Unused arguments are given no names. { } template<std::size_t I = 0, typename FuncT, typename... Tp> static typename std::enable_if < I<sizeof...(Tp), void>::type for_each(std::tuple<Tp...> t, FuncT f) { f(std::get<I>(t)); for_each<I + 1, FuncT, Tp...>(t, f); } template<typename T> static void Validate(T& obj) { constexpr auto type = refl::reflect<T>(); refl::util::for_each(type.members, [&type, &obj](auto member) { if (member.is_static || !member.is_writable) return; const auto attrs = refl::descriptor::get_attributes(member); for_each(attrs, [obj, member](const auto val) { typedef std::remove_reference_t<decltype(val)> DeclType; constexpr auto memberType = refl::reflect<DeclType>(); constexpr auto members = refl::descriptor::get_members(memberType); refl::util::apply(members, [val, member, obj](auto func) { cpp::result<void, std::string> valid = refl::descriptor::invoke(func, val, member(obj)); if (valid.has_error()) { Console::ConErr(std::format("While trying to create reflectable. Failed to validate {} (reason: {})", std::string(member.name.c_str()), valid.error())); } }); }); }); } public: /// <summary> /// Save an instance of a class/struct to a JSON file. /// Reflectable values are int, uint, bool, float, string, Reflectable, and std::vectors of the previous types. /// Exceptions will be thrown for invalid file names. /// </summary> /// <typeparam name="T">The type you want to save as an JSON file.</typeparam> /// <param name="t">The instance of the class you would like to serialize.</param> /// <param name="fileToSave">Where you would like to save the file. Defaults to empty string. If empty, the class /// meta data will be used.</param> template<typename T> inline static void SaveToJson(T& t, std::string fileToSave = "") { // If no file is provided, we can search the class metadata. if (fileToSave.empty()) { fileToSave = dynamic_cast<Reflectable&>(t).File(); if (fileToSave.empty()) { Console::ConErr("While trying to serialize, a file, both the metadata of the class and fileName were empty."); throw std::invalid_argument("While trying to serialize, a file, both the metadata of the class and fileName were empty."); } } // Create our JSON object to write auto json = nlohmann::json::object(); WriteObject(json, t); if (std::filesystem::path folderPath(fileToSave); folderPath.has_root_directory()) { folderPath.remove_filename(); if (!std::filesystem::create_directories(folderPath) && !std::filesystem::exists(folderPath)) { Console::ConWarn(std::format("Unable to create directories for {} when serializing json.", folderPath.string())); return; } } std::ofstream out(fileToSave); if (!out.good() || !out.is_open()) { Console::ConWarn(std::format("Unable to open {} for writing.", fileToSave)); return; } out << json.dump(4); out.close(); } template<typename T> inline static T JsonToObject(std::string fileName = "", bool createIfNotExist = true) { // If we cannot load, we return a default T ret; // If no file is provided, we can search the class metadata. if (fileName.empty()) { fileName = dynamic_cast<Reflectable&>(ret).File(); if (fileName.empty()) { std::string err = "While trying to deserialize, a file, both the metadata of the class and fileName were empty."; Console::ConErr(err); throw std::invalid_argument(err); } } bool exists = std::filesystem::exists(fileName); if (!exists && !createIfNotExist) { Console::ConErr(std::format("Couldn't load JSON File ({})", fileName)); return ret; } if (!exists) { // Default constructor SaveToJson(ret, fileName); return ret; } std::ifstream file(fileName); if (!file || !file.is_open() || !file.good()) { Console::ConWarn(std::format("Unable to open JSON file {}", fileName)); return ret; } try { // Load data from file. std::stringstream buffer; buffer << file.rdbuf(); file.close(); nlohmann::json json = nlohmann::json::parse(buffer.str()); ReadObject(json, ret); Validate(ret); } catch (nlohmann::json::parse_error& ex) { Console::ConErr("Unable to process JSON. It could not be parsed. See log for more detail."); AddLog(LogType::Normal, LogLevel::Warn, std::format("Unable to process JSON file [{}]. The JSON could not be parsed. EXCEPTION: {}", fileName, ex.what())); } catch (nlohmann::json::type_error& ex) { Console::ConErr("Unable to process JSON. It could not be parsed. See log for more detail."); AddLog(LogType::Normal, LogLevel::Warn, std::format("Unable to process JSON file [{}]. A type within the JSON object did not match. EXCEPTION: {}", fileName, ex.what())); } catch (nlohmann::json::exception& ex) { Console::ConErr("Unable to process JSON. It could not be parsed. See log for more detail."); AddLog(LogType::Normal, LogLevel::Warn, std::format("Unable to process JSON file [{}] EXCEPTION: {}", fileName, ex.what())); } // If we resave the file after processing, it will trim any unrelated data, and any missing fields SaveToJson(ret, fileName); return ret; } }; #endif
18,254
C++
.h
523
30.910134
158
0.674432
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,477
Attributes.hpp
TheStarport_FLHook/include/Tools/Serialization/Attributes.hpp
#pragma once #include <refl.hpp> template<typename T> requires IsNumeric<T> struct AttrMin : refl::attr::usage::field { const T val; explicit constexpr AttrMin(T v) noexcept : val(v) { // no impl } cpp::result<void, std::string> Validate(const T& comp) const { if (comp >= val) { return {}; } return cpp::fail(std::string("Value was below minimum threshold")); } }; REFL_AUTO(template((typename T), (AttrMin<T>)), func(Validate)); template<typename T> requires IsNumeric<T> struct AttrMax : refl::attr::usage::field { const T val; explicit constexpr AttrMax(T v) noexcept : val(v) { // no impl } cpp::result<void, std::string> Validate(const T& comp) const { if (comp <= val) { return {}; } return cpp::fail(std::string("Value was above maximum threshold")); } }; REFL_AUTO(template((typename T), (AttrMax<T>)), func(Validate)); template<typename T> requires StringRestriction<T> struct AttrNotEmptyNotWhiteSpace : refl::attr::usage::field { explicit constexpr AttrNotEmptyNotWhiteSpace() noexcept { // no impl } cpp::result<void, std::string> Validate(const T& comp) const { if (comp.empty() || std::ranges::all_of(comp, [](const auto& c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t'; })) { return cpp::fail(std::string("Value was empty")); } return {}; } }; REFL_AUTO(template((typename T), (AttrNotEmptyNotWhiteSpace<T>)), func(Validate)); template<typename T> requires StringRestriction<T> struct AttrMaxLength : refl::attr::usage::field { const uint val; explicit constexpr AttrMaxLength(uint v) noexcept : val(v) { // no impl } cpp::result<void, std::string> Validate(const T& comp) const { if (comp.length() > val) { return cpp::fail(std::format("Value {} was above max of {}", comp.length(), val)); } return {}; } }; REFL_AUTO(template((typename T), (AttrMaxLength<T>)), func(Validate)); template<typename T> requires StringRestriction<T> struct AttrMinLength : refl::attr::usage::field { const uint val; explicit constexpr AttrMinLength(uint v) noexcept : val(v) { // no impl } cpp::result<void, std::string> Validate(const T& comp) const { if (comp.length() < val) { return cpp::fail(std::format("Value {} was below max of {}", comp.length(), val)); } return {}; } }; REFL_AUTO(template((typename T), (AttrMinLength<T>)), func(Validate)); template<typename T> using AttrLambda = cpp::result<void, std::string>(*)(T); template<typename T, typename TT> concept LambdaConstraint = std::is_same_v<T, AttrLambda<TT>>; template<typename T, typename Lambda> struct AttrCustom : refl::attr::usage::field { Lambda func; explicit constexpr AttrCustom(const Lambda& l) noexcept : func(l) { // no impl } cpp::result<void, std::string> Validate(const T& comp) const { return func(comp); } }; REFL_AUTO(template((typename T, typename Lambda), (AttrCustom<T, Lambda>)), func(Validate)); template<typename T> struct AttrNotEmpty : refl::attr::usage::field { explicit constexpr AttrNotEmpty() noexcept { // no impl } cpp::result<void, std::string> Validate(const T& comp) const { if (comp.empty()) { return cpp::fail(std::string("Value was empty")); } return {}; } }; REFL_AUTO(template((typename T), (AttrNotEmpty<T>)), func(Validate));
3,316
C++
.h
128
23.554688
127
0.690702
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,478
Mail.hpp
TheStarport_FLHook/include/Features/Mail.hpp
#pragma once #include <FLHook.hpp> class DLL MailManager : public Singleton<MailManager> { std::string GetCharacterName(const std::variant<uint, std::wstring>& character) const; public: struct MailItem { int64 id; bool unread = true; std::string subject; std::string author; std::string body; int64 timestamp = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count(); std::string characterName; }; private: SQLite::Database db = SqlHelpers::Create("mail.sqlite"); enum class ErrorTypes { InvalidCharacter, SubjectTooLong, AuthorTooLong, BodyTooLong, MailIdNotFound }; constexpr std::string GetErrorCode(ErrorTypes err) const { std::vector<std::string> errors = {"Invalid character name or client id", "Subject cannot be longer than 32 characters.", "Author cannot be longer than 36 characters.", "Body cannot be longer than 255 characters.", "Mail id was not found." }; return errors[(int)err]; } public: MailManager(); /// <summary> /// Sends a mail to the target character, specified by ClientId or string. /// </summary> /// <param name="character">If a uint specified, it calculates to the id of the online user. Otherwise a string is used for their character name.</param> /// <param name="item">The preconstructed mail object.</param> /// <returns>Nothing in the event of success, otherwise an std::string of an err</returns> cpp::result<void, std::string> SendNewMail(const std::variant<uint, std::wstring>& character, const MailItem& item) const; /// <summary> /// Gets a list of mail from the target character, ordered by most recent. /// </summary> /// <param name="character">If a uint specified, it calculates to the id of the online user. Otherwise a string is used for their character name.</param> /// <param name="ignoreRead">If true, mail that has already been read is skipped.</param> /// <param name="page">Mail will be returned in batches of 15. The page will indicate which batch should be returned.</param> /// <returns>An std::vector of MailItem in s returned in the event of success, otherwise an std::string of an err.</returns> cpp::result<std::vector<MailItem>, std::string> GetMail(const std::variant<uint, std::wstring>& character, const bool& ignoreRead, const int& page); /// <summary> /// Get's the associated mail item by accessing it via ID and character name. /// </summary> /// <param name="character">If a uint specified, it calculates to the id of the online user. Otherwise a string is used for their character name.</param> /// <param name="index">The mail item number.</param> /// <returns>A mail item in the event of success, otherwise an std::string of err</returns> cpp::result<MailItem, std::string> GetMailById(const std::variant<uint, std::wstring>& character, const int64& index); /// <summary> /// Delete mail specified by the mail number. /// </summary> /// <param name="character">If a uint specified, it calculates to the id of the online user. Otherwise a string is used for their character name.</param> /// <param name="index">The mail item number.</param> /// <returns>Nothing in the event of success, otherwise an std::string of an err</returns> cpp::result<void, std::string> DeleteMail(const std::variant<uint, std::wstring>& character, const int64& index) const; /// <summary> /// Delete all mail on the character specified /// </summary> /// <param name="character">If a uint specified, it calculates to the id of the online user. Otherwise a string is used for their character name.</param> /// <param name="readMailOnly">If true, only mail that has been read will be purged.</param> /// <returns>An int64 listing the amount of mail deleted in the event of success, otherwise an std::string of an err</returns> cpp::result<int64, std::string> PurgeAllMail(const std::variant<uint, std::wstring>& character, const bool& readMailOnly); /// <summary> /// Changes all references to a character name within the database in the event of it being changed. /// </summary> /// <param name="oldCharacterName">The old name of the character.</param> /// <param name="newCharacterName">The new name of the character, this command will error if the name doesn't currently exist on a character.</param> // <returns>An int64 listing the number of mail items updated in the event of success, otherwise an std::string of an err</returns> cpp::result<int64, std::string> UpdateCharacterName(const std::string& oldCharacterName, const std::string& newCharacterName); /// <summary> /// Returns a number indicating the amount of mail items this character has that have not been read. /// </summary> /// <param name="character">The client id or character name.</param> // <returns>An int64 listing the number of mail items that are unread in the event of success, otherwise an std::string of an err</returns> cpp::result<int64, std::string> GetUnreadMail(const std::variant<uint, std::wstring>& character); /// <summary> /// Informs the user if they have unread mail. /// </summary> /// <param name="character">The client id or character name.</param> void SendMailNotification(const std::variant<uint, std::wstring>& character); /// <summary> /// Remove all mail that no longer have valid character references /// </summary> void CleanUpOldMail(); };
5,390
C++
.h
97
53.072165
154
0.733422
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,479
TempBan.hpp
TheStarport_FLHook/include/Features/TempBan.hpp
#include <FLHook.hpp> struct TempBanInfo { std::wstring accountId; mstime banStart = 0; mstime banEnd = 0; }; class DLL TempBanManager : public Singleton<TempBanManager> { private: std::vector<TempBanInfo> tempBanList; public: void ClearFinishedTempBans(); void AddTempBan(ClientId client, uint durationInMin, const std::wstring& reason); void AddTempBan(ClientId client, uint durationInMin); bool CheckIfTempBanned(ClientId client); };
451
C++
.h
17
24.705882
82
0.800926
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,480
ExceptionInfo.h
TheStarport_FLHook/source/ExceptionInfo.h
#pragma once /* Inspired by Dr. Dobb's "Visual C++ Exception-Handling Instrumentation" * article. * https://www.drdobbs.com/windows/visual-c-exception-handling-instrumentat/184416600 * * Additional struct information from Geoff Chappell's website. * http://www.geoffchappell.com/studies/msvc/language/predefined/ * * Modifications based on latest CRT source * Further modifications used from ExceptionalC++ Caphyon Conference * https://ciura.ro/presentations/2021/Conferences/Exceptional%20C++%20-%20Victor%20Ciura%20-%20Meeting%20C++%202021.pdf */ #include <windows.h> struct __vcrt_ptd { // C++ Exception Handling (EH) state unsigned long _NLG_dwCode; // Required by NLG routines unexpected_handler _unexpected; // unexpected() routine void* _translator; // S.E. translator void* _purecall; // called when pure virtual happens void* _curexception; // current exception void* _curcontext; // current exception context int _ProcessingThrow; // for uncaught_exception void* _curexcspec; // for handling exceptions thrown from std::unexpected int _cxxReThrow; // true if it's a rethrown C++ exception #if defined _M_X64 || defined _M_ARM || defined _M_ARM64 || defined _M_HYBRId void* _pExitContext; void* _pUnwindContext; void* _pFrameInfoChain; uintptr_t _ImageBase; uintptr_t _ThrowImageBase; void* _pForeignException; int _CatchStateInParent; // Used to link together the catch funclet with the // parent. During dispatch contains state // associated with catch in the parent. During // unwind represents the current unwind state that // is resumed to during collided unwind and used to // look for handlers of the throwing dtor. #elif defined _M_IX86 void* _pFrameInfoChain; #endif }; extern "C" __vcrt_ptd* __cdecl __current_exception_context(); inline const EXCEPTION_RECORD* GetCurrentExceptionRecord() { auto p = (__vcrt_ptd*)(((BYTE*)__current_exception_context()) - offsetof(__vcrt_ptd, _curcontext)); return (EXCEPTION_RECORD*)p->_curexception; } inline const _CONTEXT* GetCurrentExceptionContext() { auto p = (__vcrt_ptd*)(((BYTE*)__current_exception_context()) - offsetof(__vcrt_ptd, _curcontext)); return (_CONTEXT*)p->_curcontext; } //----------------------------------------------------------------------------------------------------------- // These definitions are based on assembly listings produced by the compiler // (/FAs) rather than built-in ones //----------------------------------------------------------------------------------------------------------- #pragma pack(push, ehdata, 4) struct msvc__PMD { int mdisp; int pdisp; int vdisp; }; typedef void (*msvc__PMFN)(void); #pragma warning(disable : 4200) #pragma pack(push, _TypeDescriptor, 8) struct msvc__TypeDescriptor { const void* pVFTable; void* spare; char name[]; }; #pragma pack(pop, _TypeDescriptor) #pragma warning(default : 4200) struct msvc__CatchableType { unsigned int properties; msvc__TypeDescriptor* pType; msvc__PMD thisDisplacement; int sizeOrOffset; msvc__PMFN copyFunction; }; #pragma warning(disable : 4200) struct msvc__CatchableTypeArray { int nCatchableTypes; msvc__CatchableType* arrayOfCatchableTypes[]; }; #pragma warning(default : 4200) struct msvc__ThrowInfo { unsigned int attributes; msvc__PMFN pmfnUnwind; int(__cdecl* pForwardCompat)(...); msvc__CatchableTypeArray* pCatchableTypeArray; }; #pragma pack(pop, ehdata)
3,620
C++
.h
98
33.918367
120
0.668284
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,481
xtrace.h
TheStarport_FLHook/source/xtrace.h
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * xtrace.h by Hector J. Rivas, torjo2k@hotmail.com from "ExtendedTrace" * by Zoltan Csizmadia, zoltan_csizmadia@yahoo.com * * A Win32 VC++ 6.0 implementation of the __FUNCTION__ macro that works for me. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifndef _XTRACE_H_ #define _XTRACE_H_ #if defined(_DEBUG) && defined(WIN32) #include <tchar.h> #include <windows.h> #pragma comment(lib, "imagehlp.lib") #pragma warning(disable : 4172) // returning address of a temp #define BUFFERSIZE 512 BOOL InitSymInfo(PCSTR lpszInitialSymbolPath = NULL, BOOL bSysPath = FALSE); void InitSymPath(PSTR lpszSymbolPath, PCSTR lpszIniPath, BOOL bSysPath); BOOL GetFuncInfo(ULONG fnAddress, ULONG stackAddress, LPTSTR lpszSymbol); LPCTSTR GetFuncName(); BOOL KillSymInfo(); #define __FUNCTION__ GetFuncName() #else #include <tchar.h> #include <windows.h> BOOL InitSymInfo(PCSTR); BOOL KillSymInfo(); #define __FUNCTION__ _T("") #endif #endif
1,124
C++
.h
29
35.310345
81
0.617041
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,483
Global.hpp
TheStarport_FLHook/source/Global.hpp
#pragma once #include <FLHook.hpp> bool FLHookInit(); void FLHookInit_Pre(); void FLHookShutdown(); void LoadSettings(); void ProcessPendingCommands(); void PatchClientImpl(); bool InitHookExports(); void UnloadHookExports(); void HookRehashed(); void LoadUserCharSettings(ClientId client); void ClearClientInfo(ClientId client); void LoadUserSettings(ClientId client); bool UserCmd_Process(ClientId client, const std::wstring& wscCmd); bool AllowPlayerDamage(ClientId client, ClientId clientTarget); // Logs template<typename T> std::wstring ToLogString(const T& val) { // Get type without reference typedef std::remove_reference_t<decltype(val)> DeclType; if constexpr (std::is_same_v<DeclType, int> || std::is_same_v<DeclType, uint> || std::is_same_v<DeclType, float> || std::is_same_v<DeclType, double>) { return std::to_wstring(val); } return L"<undefined>"; } // FuncCache namespace StartupCache { void Init(); void Done(); } // namespace StartupCache namespace Hk { namespace Ini { // Ini processing functions void CharacterInit(); void CharacterShutdown(); void CharacterClearClientInfo(ClientId client); void CharacterSelect(CHARACTER_ID const charId, ClientId client); } // namespace Ini namespace Personalities { void LoadPersonalities(); } namespace Client { uint ExtractClientID(const std::variant<uint, std::wstring>& player); cpp::result<CAccount*, Error> ExtractAccount(const std::variant<uint, std::wstring>& player); } // namespace Client } // namespace Hk // Death void Naked__ShipDestroyed(); // Dmg void Naked__GuidedHit(); void Naked__AddDamageEntry(); void Naked__NonGunWeaponHitsBase(); void Naked__AddDamageEntry(); void Naked__DamageHit(); void Naked__DamageHit2(); void Naked__DisconnectPacketSent(); // Timers void TimerTempBanCheck(); void TimerCheckKick(); void TimerNPCAndF1Check(); void ThreadResolver(); void TimerCheckResolveResults(); void BaseDestroyed(uint objectId, ClientId clientBy); extern HookEntry IServerImplEntries[73]; // DataBaseMarket bool LoadBaseMarket(); extern CRITICAL_SECTION csIPResolve; extern std::list<RESOLVE_IP> g_lstResolveIPs; extern std::list<RESOLVE_IP> g_lstResolveIPsResult; extern HANDLE hThreadResolver; // help void IClientImpl__Startup__Inner(uint iDunno, uint iDunno2); inline auto* ToWChar(const ushort* val) { return reinterpret_cast<const wchar_t*>(val); } inline auto* ToWChar(ushort* val) { return reinterpret_cast<wchar_t*>(val); } inline auto* ToUShort(const wchar_t* val) { return reinterpret_cast<const ushort*>(val); } inline auto* ToUShort(wchar_t* val) { return reinterpret_cast<ushort*>(val); } #define CALL_SERVER_PREAMBLE \ { \ static CTimer timer(__FUNCTION__, 100); \ timer.start(); \ TRY_HOOK \ { #define CALL_SERVER_POSTAMBLE(catchArgs, rval) \ } \ CATCH_HOOK({ \ AddLog(LogType::Normal, LogLevel::Err, std::format("Exception in {} on server call", __FUNCTION__)); \ bool ret = catchArgs; \ if (!ret) \ { \ timer.stop(); \ return rval; \ } \ }) \ timer.stop(); \ } #define CALL_CLIENT_PREAMBLE \ { \ void* vRet; \ char* tmp; \ memcpy(&tmp, &Client, 4); \ memcpy(&Client, &OldClient, 4); #define CALL_CLIENT_POSTAMBLE \ __asm { mov [vRet], eax} \ memcpy(&Client, &tmp, 4); \ } #define CHECK_FOR_DISCONNECT \ { \ if (ClientInfo[client].bDisconnected) \ { \ AddLog(LogType::Normal, LogLevel::Err, std::format("Ignoring disconnected client in {} id={}", __FUNCTION__, client)); \ return; \ }; \ } #define ADDR_UPDATE 0x1BAB4 #define ADDR_STARTUP 0x1BABC #define ADDR_SHUTDOWN 0x1BAB8 #define ADDR_ANTIdIEMSG 0x39124 #define ADDR_DISCFENCR 0x6E10D #define ADDR_DISCFENCR2 0x6BFA6 #define ADDR_CRCANTICHEAT 0x6FAF0 #define ADDR_RCSENDCHAT 0x7F30 #define ADDR_CPLIST 0x43D74 #define ADDR_CDPSERVER 0xA284 // 065CA284 #define ADDR_CREATECHAR 0x6B790 // 06D4B790 #define ADDR_FLNEW 0x80012 // 06D60012 #define ADDR_SERVERFLSERVER 0x1BC90 // 0041BC90 #define ADDR_DISABLENPCSPAWNS1 0x5987B // 06EF987B #define ADDR_DISABLENPCSPAWNS2 0x59CD3 // 06EF9CD3 #define ADDR_DATAPTR 0x277EC // 004277EC #define ADDR_RC_DISCONNECT 0x93E0 // 06B393E0 #define ADDR_DALIB_DISC_SUPPRESS 0x49C6 // 065C49C6 #define ADDR_SRV_GETCOMMODITIES 0x32EC2 // 06D12EC2 #define ADDR_SRV_MAXGROUPSIZE 0x3A068 // 06D1A068 #define ADDR_SRV_MAXGROUPSIZE2 0x3A46E // 06D1A46E #define ADDR_SRV_GETINSPECT 0x206C0 // 06D006C0 #define ADDR_SRV_PLAYERDBMAXPLAYERSPATCH 0x64BC3 #define ADDR_SRV_PLAYERDBMAXPLAYERS 0xB0264 #define ADDR_SRV_REPARRAYFREE 0x7F3F0 #define ADDR_COMMON_VFTABLE_POWER 0x1398F4 #define ADDR_COMMON_VFTABLE_SCANNER 0x139920 #define ADDR_COMMON_VFTABLE_LIGHT 0x13994C #define ADDR_COMMON_VFTABLE_TRACTOR 0x139978 #define ADDR_COMMON_VFTABLE_MINE 0x139C64 #define ADDR_COMMON_VFTABLE_CM 0x139C90 #define ADDR_COMMON_VFTABLE_GUN 0x139C38 #define ADDR_COMMON_VFTABLE_SHIELDGEN 0x139BB4 #define ADDR_COMMON_VFTABLE_THRUSTER 0x139BE0 #define ADDR_COMMON_VFTABLE_SHIELDBAT 0x1399FC #define ADDR_COMMON_VFTABLE_NANOBOT 0x1399D0 #define ADDR_COMMON_VFTABLE_MUNITION 0x139CE8 #define ADDR_COMMON_VFTABLE_ENGINE 0x139AAC class CTimer { public: EXPORT CTimer(const std::string& sFunction, uint iWarning); EXPORT void start(); EXPORT uint stop(); private: mstime tmStart = 0; uint iMax = 0; std::string sFunction; uint iWarning; }; struct PluginData { std::string name; std::string shortName; HMODULE dll = nullptr; std::wstring dllName; bool mayUnload = false; ReturnCode* returnCode = nullptr; bool resetCode = true; bool paused = false; std::vector<UserCommand>* commands; std::vector<Timer>* timers; std::shared_ptr<PluginInfo> pInfo = nullptr; }; struct PluginHookData { HookedCall targetFunction; PluginHook::FunctionType* hookFunction; HookStep step; int priority; std::shared_ptr<PluginData> plugin; }; inline bool operator<(const PluginHookData& lhs, const PluginHookData& rhs) { return lhs.priority > rhs.priority; } class PluginManager : public Singleton<PluginManager> { public: struct FunctionHookProps { bool callBefore = false; bool callAfter = false; bool matches(HookStep s) const { switch (s) { case HookStep::Before: return callBefore; case HookStep::After: return callAfter; default: return false; } } }; private: std::array<std::vector<PluginHookData>, uint(HookedCall::Count) * magic_enum::enum_count<HookStep>()> pluginHooks_; std::vector<std::shared_ptr<PluginData>> plugins_; std::unordered_map<HookedCall, FunctionHookProps> hookProps_; void clearData(bool free); void setupProps(); void setProps(HookedCall c, bool before, bool after); public: PluginManager(); ~PluginManager(); void loadAll(bool, CCmds*); void unloadAll(); void load(const std::wstring& fileName, CCmds*, bool); cpp::result<std::wstring, Error> unload(const std::string& shortName); auto begin() { return plugins_.begin(); } auto end() { return plugins_.end(); } auto begin() const { return plugins_.begin(); } auto end() const { return plugins_.end(); } template<typename ReturnType, typename... Args> ReturnType callPlugins(HookedCall target, HookStep step, bool& skipFunctionCall, Args&&... args) const { using PluginCallType = ReturnType(Args...); constexpr bool ReturnTypeIsVoid = std::is_same_v<ReturnType, void>; using NoVoidReturnType = std::conditional_t<ReturnTypeIsVoid, int, ReturnType>; NoVoidReturnType ret {}; TRY_HOOK { for (const auto& hook : pluginHooks_[uint(target) * magic_enum::enum_count<HookStep>() + uint(step)]) { const auto& plugin = hook.plugin; if (plugin->paused) continue; if (plugin->resetCode) *plugin->returnCode = ReturnCode::Default; TRY_HOOK { if constexpr (ReturnTypeIsVoid) reinterpret_cast<PluginCallType*>(hook.hookFunction)(std::forward<Args>(args)...); else ret = reinterpret_cast<PluginCallType*>(hook.hookFunction)(std::forward<Args>(args)...); } CATCH_HOOK({ AddLog(LogType::Normal, LogLevel::Err, std::format("Exception in plugin '{}' in {}", plugin->name, __FUNCTION__)); }); auto code = *plugin->returnCode; if ((code & ReturnCode::SkipFunctionCall) != ReturnCode::Default) skipFunctionCall = true; if ((code & ReturnCode::SkipPlugins) != ReturnCode::Default) break; } } CATCH_HOOK({ AddLog(LogType::Normal, LogLevel::Err, std::format("Exception {}", __FUNCTION__)); }); if constexpr (!ReturnTypeIsVoid) return ret; } }; template<typename ReturnType = void, typename... Args> auto CallPluginsBefore(HookedCall target, Args&&... args) { bool skip = false; if constexpr (std::is_same_v<ReturnType, void>) { PluginManager::i()->callPlugins<void>(target, HookStep::Before, skip, std::forward<Args>(args)...); return skip; } else { ReturnType ret = PluginManager::i()->callPlugins<ReturnType>(target, HookStep::Before, skip, std::forward<Args>(args)...); return std::make_tuple(ret, skip); } } template<typename... Args> void CallPluginsAfter(HookedCall target, Args&&... args) { bool dontCare = false; PluginManager::i()->callPlugins<void>(target, HookStep::After, dontCare, std::forward<Args>(args)...); } template<typename... Args> bool CallPluginsOther(HookedCall target, HookStep step, Args&&... args) { bool skip = false; PluginManager::i()->callPlugins<void>(target, step, skip, std::forward<Args>(args)...); return skip; } using ExportPluginInfoT = void (*)(PluginInfo*); class DebugTools : public Singleton<DebugTools> { static std::map<std::string, uint> hashMap; std::allocator<BYTE> allocator; static uint CreateIdDetour(const char* str); public: DebugTools() = default; void Init(); }; void DetourSendComm(); void UnDetourSendComm();
11,626
C++
.h
323
33.773994
150
0.6244
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,484
MemoryManager.hpp
TheStarport_FLHook/source/Memory/MemoryManager.hpp
#pragma once #include <Global.hpp> class SaveGameDetour { std::string path; static bool GetUserDataPathDetour(char* retPtr); std::string GetSaveDataPath() const; protected: void InitHook(); void DestroyHook(); }; class MemoryManager final : public SaveGameDetour, public Singleton<MemoryManager> { public: MemoryManager() = default; void AddHooks(); void RemoveHooks(); };
389
C++
.h
18
19.722222
82
0.784741
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,485
gstrealsenseplugin.cpp
WKDSMRT_realsense-gstreamer/src/gstrealsenseplugin.cpp
/* GStreamer RealSense is a set of plugins to acquire frames from * Intel RealSense cameras into GStreamer pipeline. * Copyright (C) <2020> Tim Connelly/WKD.SMRT <timpconnelly@gmail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301, USA. */ /** * SECTION:element-realsensesrc * * Source element for Intel RealSense camera. This source takes the * frame_set from the RealSense SDK and multiplexes it into a single buffer * that is pushed out on the source pad. Downstream elements may receive this buffer * and demux it themselves (use RSMux::demux) or use the rsdemux element to split * the color and depth into separate buffers. * * Example launch line * |[ * gst-launch-1.0 -v -m realsensesrc ! videoconvert ! autovideosink * ]| * * The example pipeline will display muxed data, so the depth and IMU data * will not be displayed correctly. See rsdemux element to split the sources * into seperate streams. * */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #include <gst/gst.h> #include <gst/video/video.h> #include <gst/audio/audio.h> #include "gstrealsensesrc.h" #include "gstrealsensedemux.h" #ifndef PACKAGE #define PACKAGE "realsensesrc" #endif /* entry point to initialize the plug-in * initialize the plug-in itself * register the element factories and other features */ static gboolean realsensesrc_init (GstPlugin * realsensesrc) { if (!gst_element_register (realsensesrc, "rsdemux", GST_RANK_MARGINAL, GST_TYPE_RSDEMUX)) return FALSE; if(!gst_element_register (realsensesrc, "realsensesrc", GST_RANK_PRIMARY, GST_TYPE_REALSENSESRC)) return FALSE; return TRUE; } /* gstreamer looks for this structure to register realsensesrc */ GST_PLUGIN_DEFINE ( GST_VERSION_MAJOR, GST_VERSION_MINOR, realsensesrc, "Realsense plugin", realsensesrc_init, PACKAGE_VERSION, GST_LICENSE, GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN )
2,603
C++
.cpp
74
32.77027
99
0.759921
WKDSMRT/realsense-gstreamer
30
13
12
LGPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,486
gstrealsensesrc.cpp
WKDSMRT_realsense-gstreamer/src/gstrealsensesrc.cpp
/* GStreamer RealSense is a set of plugins to acquire frames from * Intel RealSense cameras into GStreamer pipeline. * Copyright (C) <2020> Tim Connelly/WKD.SMRT <timpconnelly@gmail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301, USA. */ /** * SECTION:element-realsensesrc * * Source element for Intel RealSense camera. This source takes the * frame_set from the RealSense SDK and multiplexes it into a single buffer * that is pushed out on the source pad. Downstream elements may receive this buffer * and demux it themselves (use RSMux::demux) or use the rsdemux element to split * the color and depth into separate buffers. * * Example launch line * |[ * gst-launch-1.0 -v -m realsensesrc ! videoconvert ! autovideosink * ]| * * The example pipeline will display muxed data, so the depth and IMU data * will not be displayed correctly. See rsdemux element to split the sources * into seperate streams. * */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #include <gst/gst.h> #include <gst/video/video.h> #include <gst/audio/audio.h> #include "gstrealsensesrc.h" #include "gstrealsensedemux.h" #include "gstrealsensemeta.h" #include "rsmux.hpp" #include <cmath> GST_DEBUG_CATEGORY_STATIC (gst_realsense_src_debug); #define GST_CAT_DEFAULT gst_realsense_src_debug enum { PROP_0, PROP_CAM_SN, PROP_ALIGN, PROP_DEPTH_ON, PROP_IMU_ON }; /* the capabilities of the inputs and outputs. */ #define RSS_VIDEO_CAPS GST_VIDEO_CAPS_MAKE (GST_VIDEO_FORMATS_ALL) "," \ "multiview-mode = { mono, left, right }" \ ";" \ "video/x-bayer, format=(string) { bggr, rggb, grbg, gbrg }, " \ "width = " GST_VIDEO_SIZE_RANGE ", " \ "height = " GST_VIDEO_SIZE_RANGE ", " \ "framerate = " GST_VIDEO_FPS_RANGE ", " \ "multiview-mode = { mono, left, right }" static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src", GST_PAD_SRC, GST_PAD_ALWAYS, GST_STATIC_CAPS (GST_VIDEO_CAPS_MAKE ("{ RGB, RGBA, BGR, BGRA, GRAY16_LE, GRAY16_BE, YVYU }")) ); #define gst_realsense_src_parent_class parent_class G_DEFINE_TYPE_WITH_CODE(GstRealsenseSrc, gst_realsense_src, GST_TYPE_PUSH_SRC, GST_DEBUG_CATEGORY_INIT (gst_realsense_src_debug, "realsensesrc", 0, "Template realsensesrc")); static void gst_realsense_src_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec); static void gst_realsense_src_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec); static GstFlowReturn gst_realsense_src_create (GstPushSrc * src, GstBuffer ** buf); static gboolean gst_realsense_src_start (GstBaseSrc * basesrc); static gboolean gst_realsense_src_stop (GstBaseSrc * basesrc); static GstCaps *gst_realsense_src_get_caps (GstBaseSrc * src, GstCaps * filter); static gboolean gst_realsense_src_set_caps (GstBaseSrc * src, GstCaps * caps); static gboolean gst_realsense_src_unlock (GstBaseSrc * basesrc); static gboolean gst_realsense_src_unlock_stop (GstBaseSrc * basesrc); /* initialize the realsensesrc's class */ static void gst_realsense_src_class_init (GstRealsenseSrcClass * klass) { GObjectClass *gobject_class; GstElementClass *gstelement_class; GstBaseSrcClass *gstbasesrc_class; GstPushSrcClass *gstpushsrc_class; gobject_class = (GObjectClass *) klass; gstelement_class = (GstElementClass *) klass; gstbasesrc_class = (GstBaseSrcClass *) klass; gstpushsrc_class = (GstPushSrcClass *) klass; gobject_class->set_property = gst_realsense_src_set_property; gobject_class->get_property = gst_realsense_src_get_property; gst_element_class_set_details_simple(gstelement_class, "RealsenseSrc", "Source/Video/Sensors", "Source element for Intel RealSense multiplexed video, depth and IMU data", "Tim Connelly/WKD.SMRT <<timpconnelly@gmail.com>>"); // gst_element_class_add_pad_template (gstelement_class, // gst_static_pad_template_get (&src_factory)); gst_element_class_add_static_pad_template (gstelement_class, &src_factory); gstbasesrc_class->get_caps = gst_realsense_src_get_caps; gstbasesrc_class->set_caps = gst_realsense_src_set_caps; // gstbasesrc_class->fixate = gst_video_test_src_src_fixate; // gstbasesrc_class->is_seekable = gst_video_test_src_is_seekable; // gstbasesrc_class->do_seek = gst_video_test_src_do_seek; // gstbasesrc_class->query = gst_video_test_src_query; // gstbasesrc_class->get_times = gst_video_test_src_get_times; gstbasesrc_class->start = gst_realsense_src_start; gstbasesrc_class->stop = gst_realsense_src_stop; // gstbasesrc_class->decide_allocation = gst_video_test_src_decide_allocation; gstbasesrc_class->unlock = GST_DEBUG_FUNCPTR (gst_realsense_src_unlock); gstbasesrc_class->unlock_stop = GST_DEBUG_FUNCPTR (gst_realsense_src_unlock_stop); gstpushsrc_class->create = gst_realsense_src_create; // Properties // see Pattern property in VideoTestSrc for usage of enum propert g_object_class_install_property (gobject_class, PROP_ALIGN, g_param_spec_int ("align", "Alignment", "Alignment between Color and Depth sensors.", Align::None, Align::Depth, 0, (GParamFlags)(G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS))); g_object_class_install_property (gobject_class, PROP_DEPTH_ON, g_param_spec_int ("stream-type", "Enable Depth", "Enable streaming of depth data", StreamType::StreamColor, StreamType::StreamMux, StreamType::StreamDepth, (GParamFlags)(G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS))); g_object_class_install_property (gobject_class, PROP_IMU_ON, g_param_spec_boolean ("imu-on", "Enable IMU", "Enable streaming of IMU data", false, (GParamFlags)(G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS))); g_object_class_install_property (gobject_class, PROP_CAM_SN, g_param_spec_uint64 ("cam-serial-number", "cam-sn", "Camera serial number (as unsigned int)", 0, G_MAXUINT64, 0, (GParamFlags) (G_PARAM_READWRITE | GST_PARAM_CONTROLLABLE | G_PARAM_STATIC_STRINGS) ) ); } /* initialize the new element * instantiate pads and add them to element * set pad calback functions * initialize instance structure */ static void gst_realsense_src_init (GstRealsenseSrc * src) { /* set source as live (no preroll) */ gst_base_src_set_live (GST_BASE_SRC (src), TRUE); /* override default of BYTES to operate in time mode */ gst_base_src_set_format (GST_BASE_SRC (src), GST_FORMAT_TIME); src->stop_requested = FALSE; } static void gst_realsense_src_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec) { GstRealsenseSrc *src = GST_REALSENSESRC (object); switch (prop_id) { case PROP_CAM_SN: src->serial_number = g_value_get_uint64(value); GST_ELEMENT_WARNING (src, RESOURCE, SETTINGS, ("Received serial number %lu.", src->serial_number), (NULL)); break; case PROP_ALIGN: src->align = static_cast<Align>(g_value_get_int(value)); break; case PROP_DEPTH_ON: src->stream_type = static_cast<StreamType>(g_value_get_int(value)); break; case PROP_IMU_ON: src->imu_on = g_value_get_boolean(value); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static void gst_realsense_src_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec) { GstRealsenseSrc *src = GST_REALSENSESRC (object); switch (prop_id) { case PROP_CAM_SN: g_value_set_uint64(value, src->serial_number); break; case PROP_ALIGN: g_value_set_int(value, src->align); break; case PROP_DEPTH_ON: g_value_set_int(value, src->stream_type); break; case PROP_IMU_ON: g_value_set_boolean(value, src->imu_on); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static gboolean gst_realsense_src_unlock (GstBaseSrc * basesrc) { GstRealsenseSrc *src = GST_REALSENSESRC (basesrc); GST_LOG_OBJECT (src, "unlock"); src->stop_requested = TRUE; return TRUE; } static gboolean gst_realsense_src_unlock_stop (GstBaseSrc * basesrc) { GstRealsenseSrc *src = GST_REALSENSESRC (basesrc); GST_LOG_OBJECT (src, "unlock_stop"); src->stop_requested = FALSE; return TRUE; } static GstBuffer * gst_realsense_src_create_buffer_from_frameset (GstRealsenseSrc * src, rs2::frameset& frame_set) { auto cframe = frame_set.get_color_frame(); auto depth = frame_set.get_depth_frame(); auto header = RSHeader{ cframe.get_height(), cframe.get_width(), src->gst_stride, src->color_format, depth.get_height(), depth.get_width(), depth.get_stride_in_bytes(), src->depth_format, src->accel_format, src->gyro_format }; GST_CAT_DEBUG(gst_realsense_src_debug, "muxing data into GstBuffer"); return RSMux::mux(frame_set, header, src); } static void calculate_frame_rate(GstRealsenseSrc* src, GstClockTime new_time) { constexpr double fpns_to_fps = 1e9; const auto tdiff = new_time - src->prev_time; const auto instant_fr = fpns_to_fps * 1.0 / static_cast<double>(tdiff); const auto mean_fr = fpns_to_fps * static_cast<double>(src->frame_count) / static_cast<double>(new_time); GST_CAT_DEBUG(gst_realsense_src_debug, "Instant frame rate: %.02f, Avg frame rate: %.2f", instant_fr, mean_fr); } static GstFlowReturn gst_realsense_src_create (GstPushSrc * psrc, GstBuffer ** buf) { GstRealsenseSrc *src = GST_REALSENSESRC (psrc); GST_LOG_OBJECT (src, "create"); GST_CAT_DEBUG(gst_realsense_src_debug, "creating frame buffer"); /* wait for next frame to be available */ try { auto frame_set = src->rs_pipeline->wait_for_frames(); if(src->aligner != nullptr) frame_set = src->aligner->process(frame_set); GST_CAT_DEBUG(gst_realsense_src_debug, "received frame from realsense"); /* create GstBuffer then release */ *buf = gst_realsense_src_create_buffer_from_frameset(src, frame_set); GST_CAT_DEBUG(gst_realsense_src_debug, "setting timestamp."); const auto clock = gst_element_get_clock (GST_ELEMENT (src)); const auto clock_time = gst_clock_get_time (clock); auto tdiff = GST_CLOCK_DIFF (gst_element_get_base_time (GST_ELEMENT (src)), clock_time); GST_BUFFER_TIMESTAMP (*buf) = tdiff; GST_BUFFER_OFFSET (*buf) = frame_set.get_frame_number(); gst_object_unref (clock); ++(src->frame_count); calculate_frame_rate(src, tdiff); src->prev_time = tdiff; const auto depth_units = frame_set.get_depth_frame().get_units(); const auto exposure = static_cast<uint>(frame_set.get_frame_metadata(RS2_FRAME_METADATA_ACTUAL_EXPOSURE)); auto cstream = src->rs_pipeline->get_active_profile().get_stream(RS2_STREAM_COLOR).as<rs2::video_stream_profile>(); auto cintrinsics = cstream.get_intrinsics(); gst_buffer_add_realsense_meta(*buf, "unknown", std::to_string(src->serial_number), exposure, "", depth_units, &cintrinsics); } catch (rs2::error & e) { GST_ELEMENT_ERROR (src, RESOURCE, FAILED, ("RealSense error calling %s (%s)", e.get_failed_function().c_str(), e.get_failed_args().c_str()), (NULL)); return GST_FLOW_ERROR; } if (src->stop_requested) { if (*buf != NULL) { gst_buffer_unref (*buf); *buf = NULL; } return GST_FLOW_FLUSHING; } GST_CAT_DEBUG(gst_realsense_src_debug, "create method done"); return GST_FLOW_OK; } static GstVideoFormat RS_to_Gst_Video_Format(rs2_format fmt) { switch(fmt){ case RS2_FORMAT_RGB8: return GST_VIDEO_FORMAT_RGB; case RS2_FORMAT_BGR8: return GST_VIDEO_FORMAT_BGR; case RS2_FORMAT_RGBA8: return GST_VIDEO_FORMAT_RGBA; case RS2_FORMAT_BGRA8: return GST_VIDEO_FORMAT_BGRA; case RS2_FORMAT_Z16: case RS2_FORMAT_RAW16: case RS2_FORMAT_Y16: if (G_BYTE_ORDER == G_LITTLE_ENDIAN) { return GST_VIDEO_FORMAT_GRAY16_LE; } else if (G_BYTE_ORDER == G_BIG_ENDIAN) { return GST_VIDEO_FORMAT_GRAY16_BE; } case RS2_FORMAT_YUYV: // FIXME Not exact format match return GST_VIDEO_FORMAT_YVYU; default: return GST_VIDEO_FORMAT_UNKNOWN; } } static GstAudioFormat RS_to_Gst_Audio_Format(rs2_format fmt) { switch(fmt){ case RS2_FORMAT_XYZ32F: case RS2_FORMAT_MOTION_XYZ32F: return GST_AUDIO_FORMAT_F32; default: return GST_AUDIO_FORMAT_UNKNOWN; } } /* Adapted from librealsense/example/motion/rs-motion.cpp */ bool check_imu_is_supported(const rs2::device& dev) { bool found_gyro = false; bool found_accel = false; rs2::context ctx; // The same device should support gyro and accel found_gyro = false; found_accel = false; for (auto sensor : dev.query_sensors()) { for (auto profile : sensor.get_stream_profiles()) { if (profile.stream_type() == RS2_STREAM_GYRO) found_gyro = true; if (profile.stream_type() == RS2_STREAM_ACCEL) found_accel = true; } } return found_gyro && found_accel; } static gboolean gst_realsense_src_start (GstBaseSrc * basesrc) { auto *src = GST_REALSENSESRC (basesrc); // GST_OBJECT_LOCK (src); try { GST_LOG_OBJECT(src, "Creating RealSense pipeline"); src->rs_pipeline = std::make_unique<rs2::pipeline>(); if(src->rs_pipeline == nullptr) { GST_ELEMENT_ERROR (src, RESOURCE, FAILED, ("Failed to create RealSense pipeline."), (NULL)); return FALSE; } rs2::config cfg; rs2::context ctx; const auto dev_list = ctx.query_devices(); auto serial_number = std::to_string(src->serial_number); if(dev_list.size() == 0) { GST_ELEMENT_ERROR (src, RESOURCE, FAILED, ("No RealSense devices found. Cannot start pipeline."), (NULL)); return FALSE; } if(src->serial_number == DEFAULT_PROP_CAM_SN) { serial_number = std::string(dev_list[0].get_info(RS2_CAMERA_INFO_SERIAL_NUMBER)); } else { auto val = dev_list.begin(); for (; val != dev_list.end(); ++val) { if (0 == serial_number.compare(val.operator*().get_info(RS2_CAMERA_INFO_SERIAL_NUMBER))) { break; } } if (val == dev_list.end()) { GST_ELEMENT_WARNING(src, RESOURCE, FAILED, ("Specified serial number %lu not found. Using first found device.", src->serial_number), (NULL)); serial_number = dev_list[0].get_info(RS2_CAMERA_INFO_SERIAL_NUMBER); } } cfg.enable_device(serial_number); cfg.enable_stream(RS2_STREAM_ACCEL, RS2_FORMAT_MOTION_XYZ32F); cfg.enable_stream(RS2_STREAM_GYRO, RS2_FORMAT_MOTION_XYZ32F); cfg.enable_stream(RS2_STREAM_COLOR, RS2_FORMAT_RGB8); cfg.enable_stream(RS2_STREAM_DEPTH, RS2_FORMAT_Z16); // auto profile = src->rs_pipeline->get_active_profile(); // auto streams = profile.get_streams(); // auto s0 = streams[0].get(); switch(src->align) { case Align::None: break; case Align::Color: src->aligner = std::make_unique<rs2::align>(RS2_STREAM_COLOR); break; case Align::Depth: src->aligner = std::make_unique<rs2::align>(RS2_STREAM_DEPTH); break; default: GST_ELEMENT_WARNING (src, RESOURCE, SETTINGS, ("Unknown alignment parameter %d", src->align), (NULL)); } src->rs_pipeline->start(cfg); src->has_imu = check_imu_is_supported(src->rs_pipeline->get_active_profile().get_device()); GST_LOG_OBJECT(src, "RealSense pipeline started"); auto frame_set = src->rs_pipeline->wait_for_frames(); if(src->aligner != nullptr) frame_set = src->aligner->process(frame_set); int height = 0; int width = 0; GstVideoFormat fmt = GST_VIDEO_FORMAT_UNKNOWN; if(src->stream_type == StreamType::StreamColor) { auto cframe = frame_set.get_color_frame(); height = cframe.get_height(); width = cframe.get_width(); src->color_format = RS_to_Gst_Video_Format(cframe.get_profile().format()); fmt = src->color_format; } else if(src->stream_type == StreamType::StreamDepth) { auto depth = frame_set.get_depth_frame(); height = depth.get_height(); width = depth.get_width(); src->depth_format = RS_to_Gst_Video_Format(depth.get_profile().format()); fmt = src->depth_format; } else if(src->stream_type == StreamType::StreamMux) { auto depth = frame_set.get_depth_frame(); auto cframe = frame_set.get_color_frame(); height = cframe.get_height(); width = cframe.get_width(); src->depth_format = RS_to_Gst_Video_Format(depth.get_profile().format()); src->color_format = RS_to_Gst_Video_Format(cframe.get_profile().format()); auto depth_height = depth.get_height(); height += (depth_height * depth.get_stride_in_bytes()) / cframe.get_stride_in_bytes(); fmt = src->color_format; if(src->has_imu && src->imu_on) { src->accel_format = RS_to_Gst_Audio_Format(frame_set.first_or_default(RS2_STREAM_ACCEL).get_profile().format()); src->gyro_format = RS_to_Gst_Audio_Format(frame_set.first_or_default(RS2_STREAM_GYRO).get_profile().format()); constexpr auto imu_size = 2 * sizeof(rs2_vector); // add enough for imu data height += std::ceil(imu_size / cframe.get_stride_in_bytes()); } } gst_video_info_init(&src->info); if(fmt ==GST_VIDEO_FORMAT_UNKNOWN) GST_ELEMENT_ERROR (src, RESOURCE, FAILED, ("Unhandled RealSense format %d", fmt), (NULL)); gst_video_info_set_format(&src->info, fmt, width, height); src->caps = gst_video_info_to_caps (&src->info); } catch (rs2::error & e) { GST_ERROR_OBJECT ( src, "Realsense error calling %s (%s)", e.get_failed_function().c_str(), e.get_failed_args().c_str()); GST_ELEMENT_ERROR (src, RESOURCE, FAILED, ("RealSense error calling %s (%s)", e.get_failed_function().c_str(), e.get_failed_args().c_str()), (NULL)); return FALSE; } src->height = src->info.height; src->gst_stride = GST_VIDEO_INFO_COMP_STRIDE (&src->info, 0); // GST_OBJECT_UNLOCK (src); return TRUE; } static gboolean gst_realsense_src_stop (GstBaseSrc * basesrc) { auto *src = GST_REALSENSESRC (basesrc); if(src->rs_pipeline != nullptr) src->rs_pipeline->stop(); return TRUE; } static GstCaps * gst_realsense_src_get_caps (GstBaseSrc * bsrc, GstCaps * filter) { GstRealsenseSrc *src = GST_REALSENSESRC (bsrc); GstCaps *caps; if (src->rs_pipeline == nullptr) { caps = gst_pad_get_pad_template_caps (GST_BASE_SRC_PAD (src)); } else { caps = gst_caps_copy (src->caps); } GST_DEBUG_OBJECT (src, "The caps before filtering are %" GST_PTR_FORMAT, caps); if (filter && caps) { GstCaps *tmp = gst_caps_intersect (caps, filter); gst_caps_unref (caps); caps = tmp; } GST_DEBUG_OBJECT (src, "The caps after filtering are %" GST_PTR_FORMAT, caps); return caps; } static gboolean gst_realsense_src_set_caps (GstBaseSrc * bsrc, GstCaps * caps) { GstRealsenseSrc *src = GST_REALSENSESRC (bsrc); GstVideoInfo vinfo; // GstStructure *s = gst_caps_get_structure (caps, 0); GST_DEBUG_OBJECT (src, "The caps being set are %" GST_PTR_FORMAT, caps); gst_video_info_from_caps (&vinfo, caps); if (GST_VIDEO_INFO_FORMAT (&vinfo) != GST_VIDEO_FORMAT_UNKNOWN) { src->gst_stride = GST_VIDEO_INFO_COMP_STRIDE (&vinfo, 0); } else { goto unsupported_caps; } return TRUE; unsupported_caps: GST_ERROR_OBJECT (src, "Unsupported caps: %" GST_PTR_FORMAT, caps); return FALSE; }
21,143
C++
.cpp
544
33.360294
128
0.664591
WKDSMRT/realsense-gstreamer
30
13
12
LGPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,487
gstrealsensedemux.cpp
WKDSMRT_realsense-gstreamer/src/gstrealsensedemux.cpp
/* GStreamer RealSense is a set of plugins to acquire frames from * Intel RealSense cameras into GStreamer pipeline. * Copyright (C) <2020> Tim Connelly/WKD.SMRT <timpconnelly@gmail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301, USA. */ /* GStreamer realsense demux * * SECTION:element-rsdemux * @title: rsdemux * * Demuxer element to complement realsensesrc. * rsdemux splits muxed Realsense stream into its color and depth components. * * ## Example launch line * |[ * gst-launch-1.0 -vvv -m realsensesrc stream-type=2 align=0 imu_on=True ! rsdemux name=demux \ * ! queue ! videoconvert ! autovideosink \ * demux. ! queue ! videoconvert ! autovideosink \ * demux. ! queue ! fakesink * ]| * * This pipeline captures realsense stream, demuxes it to color and depth * and renders them to videosinks. * */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <gst/video/video.h> #include <gst/audio/audio.h> #include "gstrealsensedemux.h" #include "gstrealsensesrc.h" #include "gstrealsensemeta.h" #include "rsmux.hpp" #include <stdexcept> GST_DEBUG_CATEGORY_STATIC (rsdemux_debug); #define GST_CAT_DEFAULT rsdemux_debug #define RSS_VIDEO_CAPS GST_VIDEO_CAPS_MAKE (GST_VIDEO_FORMATS_ALL) "," \ "multiview-mode = { mono, left, right }" \ ";" \ "video/x-bayer, format=(string) { bggr, rggb, grbg, gbrg }, " \ "width = " GST_VIDEO_SIZE_RANGE ", " \ "height = " GST_VIDEO_SIZE_RANGE ", " \ "framerate = " GST_VIDEO_FPS_RANGE ", " \ "multiview-mode = { mono, left, right }" static GstStaticPadTemplate sink_tmpl = GST_STATIC_PAD_TEMPLATE ("sink", GST_PAD_SINK, GST_PAD_ALWAYS, GST_STATIC_CAPS (GST_VIDEO_CAPS_MAKE ("{ RGB, RGBA, BGR, BGRA, GRAY16_LE, GRAY16_BE, YVYU }")) ); static GstStaticPadTemplate color_src_tmpl = GST_STATIC_PAD_TEMPLATE ("color", GST_PAD_SRC, GST_PAD_SOMETIMES, GST_STATIC_CAPS (GST_VIDEO_CAPS_MAKE ("{ RGB, RGBA, BGR, BGRA, GRAY16_LE, GRAY16_BE, YVYU }")) ); static GstStaticPadTemplate depth_src_tmpl = GST_STATIC_PAD_TEMPLATE ("depth", GST_PAD_SRC, GST_PAD_SOMETIMES, GST_STATIC_CAPS (GST_VIDEO_CAPS_MAKE ("{ GRAY16_LE, GRAY16_BE }")) ); static GstStaticPadTemplate imu_src_templ = GST_STATIC_PAD_TEMPLATE ("imu", GST_PAD_SRC, GST_PAD_SOMETIMES, GST_STATIC_CAPS ("audio/x-raw, " "format = (string) " GST_AUDIO_NE (F32) ", " "layout = (string) interleaved, " "rate = (int) { 32000, 44100, 48000 }, " "channels = (int) {3, 6}") ); #define gst_rsdemux_parent_class parent_class G_DEFINE_TYPE_WITH_CODE (GstRSDemux, gst_rsdemux, GST_TYPE_ELEMENT, GST_DEBUG_CATEGORY_INIT(rsdemux_debug, "rsdemux", 0, "Demux element for Realsense plugin")); static void gst_rsdemux_finalize (GObject * object); /* query functions */ static gboolean gst_rsdemux_src_query (GstPad * pad, GstObject * parent, GstQuery * query); static gboolean gst_rsdemux_sink_query (GstPad * pad, GstObject * parent, GstQuery * query); /* event functions */ static gboolean gst_rsdemux_send_event (GstElement * element, GstEvent * event); static gboolean gst_rsdemux_handle_src_event (GstPad * pad, GstObject * parent, GstEvent * event); static gboolean gst_rsdemux_handle_sink_event (GstPad * pad, GstObject * parent, GstEvent * event); /* scheduling functions */ static GstFlowReturn gst_rsdemux_flush (GstRSDemux * rsdemux); static GstFlowReturn gst_rsdemux_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer); /* state change functions */ static GstStateChangeReturn gst_rsdemux_change_state (GstElement * element, GstStateChange transition); static void gst_rsdemux_class_init (GstRSDemuxClass * klass) { GObjectClass *gobject_class; GstElementClass *gstelement_class; gobject_class = (GObjectClass *) klass; gstelement_class = (GstElementClass *) klass; gobject_class->finalize = gst_rsdemux_finalize; gstelement_class->change_state = GST_DEBUG_FUNCPTR (gst_rsdemux_change_state); gstelement_class->send_event = GST_DEBUG_FUNCPTR (gst_rsdemux_send_event); gst_element_class_add_static_pad_template (gstelement_class, &sink_tmpl); gst_element_class_add_static_pad_template (gstelement_class, &color_src_tmpl); gst_element_class_add_static_pad_template (gstelement_class, &depth_src_tmpl); gst_element_class_add_static_pad_template (gstelement_class, &imu_src_templ); gst_element_class_set_static_metadata (gstelement_class, "RealSense Source Demuxer", "Realsense Demuxer", "Separate RealSense muxed stream into components: color, depth, IMU", "Tim Connelly/WKD.SMRT <timpconnelly@gmail.com>"); GST_DEBUG_CATEGORY_INIT (rsdemux_debug, "rsdemux", 0, "RS demuxer element"); } static void gst_rsdemux_init (GstRSDemux * rsdemux) { rsdemux->sinkpad = gst_pad_new_from_static_template (&sink_tmpl, "sink"); /* for push mode, this is the chain function */ gst_pad_set_chain_function (rsdemux->sinkpad, GST_DEBUG_FUNCPTR (gst_rsdemux_chain)); /* handling events (in push mode only) */ gst_pad_set_event_function (rsdemux->sinkpad, GST_DEBUG_FUNCPTR (gst_rsdemux_handle_sink_event)); /* query functions */ gst_pad_set_query_function (rsdemux->sinkpad, GST_DEBUG_FUNCPTR (gst_rsdemux_sink_query)); /* now add the pad */ gst_element_add_pad (GST_ELEMENT (rsdemux), rsdemux->sinkpad); // src pads will be created in the chain function } static void gst_rsdemux_finalize (GObject * object) { G_OBJECT_CLASS (parent_class)->finalize (object); } /* reset to default values before starting streaming */ static void gst_rsdemux_reset (GstRSDemux * rsdemux) { rsdemux->in_height = 0; rsdemux->in_width = 0; rsdemux->in_stride_bytes = 0; rsdemux->header = {}; } static GstPad * gst_rsdemux_add_pad (GstRSDemux * rsdemux, GstStaticPadTemplate * templ, GstCaps * caps, std::string&& stream_name) { GstPad *pad; GstEvent *event; gchar *stream_id; pad = gst_pad_new_from_static_template (templ, templ->name_template); gst_pad_set_query_function (pad, GST_DEBUG_FUNCPTR (gst_rsdemux_src_query)); gst_pad_set_event_function (pad, GST_DEBUG_FUNCPTR (gst_rsdemux_handle_src_event)); gst_pad_use_fixed_caps (pad); gst_pad_set_active (pad, TRUE); stream_id = gst_pad_create_stream_id (pad, GST_ELEMENT_CAST (rsdemux), stream_name.c_str()); event = gst_event_new_stream_start (stream_id); gst_pad_push_event (pad, event); g_free (stream_id); gst_pad_set_caps (pad, caps); gst_element_add_pad (GST_ELEMENT (rsdemux), pad); return pad; } static void gst_rsdemux_remove_pads (GstRSDemux * rsdemux) { if (rsdemux->colorsrcpad) { gst_element_remove_pad (GST_ELEMENT (rsdemux), rsdemux->colorsrcpad); rsdemux->colorsrcpad = nullptr; } if (rsdemux->depthsrcpad) { gst_element_remove_pad (GST_ELEMENT (rsdemux), rsdemux->depthsrcpad); rsdemux->depthsrcpad = nullptr; } if (rsdemux->imusrcpad) { gst_element_remove_pad (GST_ELEMENT (rsdemux), rsdemux->imusrcpad); rsdemux->imusrcpad = nullptr; } } static gboolean gst_rsdemux_src_query (GstPad * pad, GstObject * parent, GstQuery * query) { gboolean res = TRUE; // TODO Handle any necessary src queries switch (GST_QUERY_TYPE (query)) { case GST_QUERY_DURATION: default: res = gst_pad_query_default (pad, parent, query); break; } return res; } static gboolean gst_rsdemux_sink_query (GstPad * pad, GstObject * parent, GstQuery * query) { gboolean res = TRUE; // TODO Handle any sink queries switch (GST_QUERY_TYPE (query)) { case GST_QUERY_DURATION: default: res = gst_pad_query_default (pad, parent, query); break; } return res; } /* takes ownership of the event */ static gboolean gst_rsdemux_push_event (GstRSDemux * rsdemux, GstEvent * event) { gboolean res = FALSE; if (rsdemux->colorsrcpad) { gst_event_ref (event); res |= gst_pad_push_event (rsdemux->colorsrcpad, event); } if (rsdemux->depthsrcpad) { gst_event_ref (event); res |= gst_pad_push_event (rsdemux->depthsrcpad, event); } if (rsdemux->colorsrcpad==nullptr && rsdemux->depthsrcpad==nullptr) { gst_event_unref (event); res = TRUE; } return res; } static gboolean gst_rsdemux_handle_sink_event (GstPad * pad, GstObject * parent, GstEvent * event) { GstRSDemux *rsdemux = GST_RSDEMUX (parent); gboolean res = TRUE; switch (GST_EVENT_TYPE (event)) { case GST_EVENT_FLUSH_START: /* we are not blocking on anything except the push() calls * to the peer which will be unblocked by forwarding the * event.*/ res = gst_rsdemux_push_event (rsdemux, event); break; case GST_EVENT_FLUSH_STOP: res = gst_rsdemux_push_event (rsdemux, event); break; case GST_EVENT_EOS: /* flush any pending data, should be nothing left. */ gst_rsdemux_flush (rsdemux); /* forward event */ res = gst_rsdemux_push_event (rsdemux, event); /* and clear the adapter */ // gst_adapter_clear (rsdemux->adapter); break; case GST_EVENT_CAPS: gst_event_unref (event); break; default: res = gst_rsdemux_push_event (rsdemux, event); break; } return res; } static gboolean gst_rsdemux_send_event (GstElement * element, GstEvent * event) { gboolean res = FALSE; switch (GST_EVENT_TYPE (event)) { default: res = GST_ELEMENT_CLASS (parent_class)->send_event (element, event); break; } return res; } /* handle an event on the source pad, it's most likely a seek */ static gboolean gst_rsdemux_handle_src_event (GstPad * pad, GstObject * parent, GstEvent * event) { gboolean res = FALSE; const auto rsdemux = GST_RSDEMUX (parent); switch (GST_EVENT_TYPE (event)) { // TODO handle src pad events here default: res = gst_pad_push_event (rsdemux->sinkpad, event); break; } return res; } static GstFlowReturn make_new_pads(GstRSDemux* rsdemux, const RSHeader& header) { rsdemux->header = header; GST_CAT_WARNING(rsdemux_debug, "making new pads"); GST_CAT_DEBUG(rsdemux_debug, "making pad caps"); auto color_caps = gst_caps_new_simple ("video/x-raw", "format", G_TYPE_STRING, "RGB", "width", G_TYPE_INT, header.color_width, "height", G_TYPE_INT, header.color_height, "framerate", GST_TYPE_FRACTION, 30, 1, NULL); auto depth_caps = gst_caps_new_simple ("video/x-raw", "format", G_TYPE_STRING, "GRAY16_LE", "width", G_TYPE_INT, header.depth_width, "height", G_TYPE_INT, header.depth_height, "framerate", GST_TYPE_FRACTION, 30, 1, NULL); bool imu_on = GST_AUDIO_FORMAT_UNKNOWN != static_cast<GstAudioFormat>(header.accel_format); if(imu_on)// || G_UNLIKELY(rsdemux->imusrcpad==nullptr)) { GstAudioInfo info; constexpr gint imu_rate = GST_AUDIO_DEF_RATE; constexpr gint imu_channels = 6; // x,y,z for accel and gyro gst_audio_info_init(&info); gst_audio_info_set_format(&info, static_cast<GstAudioFormat>(header.accel_format), imu_rate, imu_channels, NULL); const auto imu_caps = gst_audio_info_to_caps(&info); rsdemux->imusrcpad = gst_rsdemux_add_pad(rsdemux, &imu_src_templ, imu_caps, "imu"); gst_pad_set_caps (rsdemux->imusrcpad, imu_caps); gst_caps_unref(imu_caps); } GST_CAT_DEBUG(rsdemux_debug, "made pad caps"); if (G_UNLIKELY (rsdemux->colorsrcpad == nullptr) || G_UNLIKELY(rsdemux->depthsrcpad==nullptr)) { GST_CAT_DEBUG(rsdemux_debug, "adding pads"); rsdemux->colorsrcpad = gst_rsdemux_add_pad (rsdemux, &color_src_tmpl, color_caps, "color"); rsdemux->depthsrcpad = gst_rsdemux_add_pad (rsdemux, &depth_src_tmpl, depth_caps, "depth"); if (rsdemux->colorsrcpad && rsdemux->depthsrcpad && rsdemux->imusrcpad) gst_element_no_more_pads (GST_ELEMENT (rsdemux)); } else { gst_pad_set_caps (rsdemux->colorsrcpad, color_caps); gst_pad_set_caps (rsdemux->depthsrcpad, depth_caps); } gst_caps_unref (color_caps); gst_caps_unref (depth_caps); return GST_FLOW_OK; } static GstFlowReturn gst_rsdemux_demux_video (GstRSDemux * rsdemux, GstBuffer * buffer) { GstFlowReturn ret = GST_FLOW_OK; GST_DEBUG ("Demuxing video frame"); const auto header = RSMux::GetRSHeader(rsdemux, buffer); // see if anything changed if (rsdemux->header != header || G_UNLIKELY (rsdemux->colorsrcpad == nullptr) || G_UNLIKELY (rsdemux->depthsrcpad == nullptr)) { gst_rsdemux_remove_pads(rsdemux); make_new_pads(rsdemux, header); } /* takes ownership of buffer here, we just need to modify * the metadata. */ // outbuf = gst_buffer_make_writable (buffer); auto [colorbuf, depthbuf, imubuf] = RSMux::demux(buffer, header); // meta GST_CAT_DEBUG(rsdemux_debug, "copying metadata"); auto rsmeta = gst_buffer_get_realsense_meta(buffer); gst_buffer_add_realsense_meta(colorbuf, *rsmeta->cam_model, *rsmeta->cam_serial_number,rsmeta->exposure,*rsmeta->json_descr, rsmeta->depth_units, &rsmeta->color_intrinsics); gst_buffer_add_realsense_meta(depthbuf, *rsmeta->cam_model, *rsmeta->cam_serial_number,rsmeta->exposure,*rsmeta->json_descr, rsmeta->depth_units, &rsmeta->color_intrinsics); if(imubuf != nullptr && rsdemux->imusrcpad != nullptr) gst_buffer_add_realsense_meta(imubuf, *rsmeta->cam_model, *rsmeta->cam_serial_number,rsmeta->exposure,*rsmeta->json_descr, rsmeta->depth_units, &rsmeta->color_intrinsics); GST_CAT_DEBUG(rsdemux_debug, "pushing buffers"); ret = gst_pad_push (rsdemux->colorsrcpad, colorbuf); if (ret != GST_FLOW_OK) GST_ELEMENT_WARNING(rsdemux, RESOURCE, SETTINGS, ("Pushing to color src gave %d.", ret), (NULL)); ret = gst_pad_push (rsdemux->depthsrcpad, depthbuf); if (ret != GST_FLOW_OK) GST_ELEMENT_WARNING(rsdemux, RESOURCE, SETTINGS, ("Pushing to depth src gave %d.", ret), (NULL)); if(imubuf != nullptr && rsdemux->imusrcpad != nullptr) { ret = gst_pad_push (rsdemux->imusrcpad, imubuf); if (ret != GST_FLOW_OK) GST_ELEMENT_WARNING(rsdemux, RESOURCE, SETTINGS, ("Pushing to IMU src gave %d.", ret), (NULL)); } gst_buffer_unref(buffer); return ret; } /* takes ownership of buffer */ static GstFlowReturn gst_rsdemux_demux_frame (GstRSDemux * rsdemux, GstBuffer * buffer) { GstFlowReturn vret, ret; rsdemux->frame_count++; GST_CAT_DEBUG(rsdemux_debug, "demuxing frame"); /* takes ownership of buffer */ try { vret = ret = gst_rsdemux_demux_video (rsdemux, buffer); if (G_UNLIKELY (ret != GST_FLOW_OK && ret != GST_FLOW_NOT_LINKED)) { GST_ELEMENT_ERROR(rsdemux, RESOURCE, FAILED, ("gst_rsdemux_demux_frame: %d, state=%d", ret, rsdemux->state_change), (NULL)); } /* if both are not linked, we stop */ if (G_UNLIKELY (vret == GST_FLOW_NOT_LINKED)) { ret = GST_FLOW_NOT_LINKED; } } catch(const std::exception& e) { GST_ELEMENT_ERROR (rsdemux, RESOURCE, FAILED, ("gst_rsdemux_demux_frame: %s", e.what()), (NULL)); } return ret; } static GstFlowReturn gst_rsdemux_flush (GstRSDemux * rsdemux) { // TODO What do we need to do in _flush? return GST_FLOW_OK; } // streaming operation static GstFlowReturn gst_rsdemux_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer) { GstFlowReturn ret; auto rsdemux = GST_RSDEMUX (parent); ret = gst_rsdemux_demux_frame(rsdemux, buffer); return ret; } static GstStateChangeReturn gst_rsdemux_change_state (GstElement * element, GstStateChange transition) { GstRSDemux *rsdemux = GST_RSDEMUX (element); GstStateChangeReturn ret; rsdemux->state_change = transition; // upward transitions switch (transition) { case GST_STATE_CHANGE_NULL_TO_READY: break; case GST_STATE_CHANGE_READY_TO_PAUSED: gst_rsdemux_reset (rsdemux); break; case GST_STATE_CHANGE_PAUSED_TO_PLAYING: break; default: break; } ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition); // downward transitions switch (transition) { case GST_STATE_CHANGE_PLAYING_TO_PAUSED: break; case GST_STATE_CHANGE_PAUSED_TO_READY: gst_rsdemux_remove_pads (rsdemux); break; case GST_STATE_CHANGE_READY_TO_NULL: break; default: break; } return ret; }
17,109
C++
.cpp
454
33.986784
175
0.697787
WKDSMRT/realsense-gstreamer
30
13
12
LGPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,488
gstrealsensemeta.cpp
WKDSMRT_realsense-gstreamer/src/gstrealsensemeta.cpp
/* GStreamer RealSense is a set of plugins to acquire frames from * Intel RealSense cameras into GStreamer pipeline. * Copyright (C) <2020> Tim Connelly/WKD.SMRT <timpconnelly@gmail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include <gst/gst.h> #include <gst/video/video.h> #include <gstrealsensemeta.h> #include <librealsense2/rs.hpp> #include <iostream> GType gst_realsense_meta_api_get_type (void) { static volatile GType type; if (g_once_init_enter (&type)) { static const gchar *tags[] = { GST_META_TAG_VIDEO_STR, "sensor", NULL }; GType _type = gst_meta_api_type_register ("GstRealsenseMetaAPI", tags); GST_INFO ("registering"); g_once_init_leave (&type, _type); } return type; } static gboolean gst_realsense_meta_transform (GstBuffer * dest, GstMeta * meta, GstBuffer * buffer, GQuark type, gpointer data) { GstRealsenseMeta* source_meta = reinterpret_cast<GstRealsenseMeta*>(meta); GstRealsenseMeta* dest_meta = nullptr; if(GST_META_TRANSFORM_IS_COPY(type)) { dest_meta = gst_buffer_add_realsense_meta( dest, *source_meta->cam_model, *source_meta->cam_serial_number, source_meta->exposure, *source_meta->json_descr, source_meta->depth_units, &(source_meta->color_intrinsics)); } return dest_meta != nullptr; } static gboolean gst_realsense_meta_init (GstMeta * meta, gpointer params, GstBuffer * buffer) { GstRealsenseMeta* rsmeta = reinterpret_cast<GstRealsenseMeta*>(meta); rsmeta->cam_model = nullptr; rsmeta->cam_serial_number = nullptr; rsmeta->json_descr = nullptr; rsmeta->exposure = 0; rsmeta->depth_units = 0.f; rsmeta->color_intrinsics = {}; return TRUE; } static void gst_realsense_meta_free (GstMeta * meta, GstBuffer * buffer) { auto rsmeta = reinterpret_cast<GstRealsenseMeta*>(meta); delete rsmeta->cam_model; delete rsmeta->cam_serial_number; delete rsmeta->json_descr; rsmeta->exposure = 0; rsmeta->depth_units = 0.f; rsmeta->color_intrinsics = {}; } const GstMetaInfo * gst_realsense_meta_get_info (void) { static const GstMetaInfo *meta_info = NULL; if (g_once_init_enter ((GstMetaInfo **) & meta_info)) { const GstMetaInfo *mi = gst_meta_register (GST_REALSENSE_META_API_TYPE, "GstRealsenseMeta", sizeof (GstRealsenseMeta), gst_realsense_meta_init, gst_realsense_meta_free, gst_realsense_meta_transform); g_once_init_leave ((GstMetaInfo **) & meta_info, (GstMetaInfo *) mi); } return meta_info; } GstRealsenseMeta* gst_buffer_add_realsense_meta (GstBuffer * buffer, const std::string model, const std::string serial_number, const uint exposure, const std::string json_descr, float depth_units, const rs2_intrinsics* color_intrinsics) { g_return_val_if_fail (GST_IS_BUFFER (buffer), nullptr); auto meta = reinterpret_cast<GstRealsenseMeta*>(gst_buffer_add_meta(buffer, GST_REALSENSE_META_INFO, nullptr)); meta->cam_model = new std::string(model); meta->cam_serial_number = new std::string(serial_number); meta->json_descr = new std::string(json_descr); meta->exposure = exposure; meta->depth_units = depth_units; meta->color_intrinsics = *color_intrinsics; return meta; } float gst_buffer_realsense_get_depth_meta(GstBuffer* buffer) { if(buffer == nullptr) return 0.f; GstRealsenseMeta* meta = gst_buffer_get_realsense_meta(buffer); if (meta != nullptr) { return meta->depth_units; } else { return 0.f; } } rs2_intrinsics* gst_buffer_realsense_meta_get_instrinsics(GstBuffer* buffer) { if(buffer == nullptr) return nullptr; GstRealsenseMeta* meta = gst_buffer_get_realsense_meta(buffer); if (meta != nullptr) { return &(meta->color_intrinsics); } return nullptr; }
4,954
C++
.cpp
134
30.231343
107
0.652963
WKDSMRT/realsense-gstreamer
30
13
12
LGPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,489
rsmux.hpp
WKDSMRT_realsense-gstreamer/src/rsmux.hpp
/* GStreamer RealSense is a set of plugins to acquire frames from * Intel RealSense cameras into GStreamer pipeline. * Copyright (C) <2020> Tim Connelly/WKD.SMRT <timpconnelly@gmail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef __GST_RSMUX_H__ #define __GST_RSMUX_H__ #include <gst/gst.h> #include <gst/video/video.h> #include <librealsense2/rs.hpp> #include "common.hpp" #include <iostream> #include <tuple> #include <cstring> using buf_tuple = std::tuple<GstBuffer*, GstBuffer*, GstBuffer*>; class RSMux { public: template <typename Element> static RSHeader GetRSHeader(Element* src, GstBuffer* buffer) { RSHeader header; RSHeader* in; GstMapInfo map; gst_buffer_map(buffer, &map, GST_MAP_READ); in = reinterpret_cast<RSHeader*>(map.data); header.color_height = in->color_height; header.color_width = in->color_width; header.color_stride = in->color_stride; header.color_format = in->color_format; header.depth_height = in->depth_height; header.depth_width = in->depth_width; header.depth_stride = in->depth_stride; header.depth_format = in->depth_format; header.accel_format = in->accel_format; header.gyro_format = in->gyro_format; gst_buffer_unmap(buffer, &map); return header; } static GstBuffer* mux(rs2::frameset& frame_set, const RSHeader& header, const GstRealsenseSrc* src) { GstMapInfo minfo; GstBuffer *buffer; auto cframe = frame_set.get_color_frame(); auto color_sz = static_cast<size_t>(cframe.get_height() * src->gst_stride); auto depth = frame_set.get_depth_frame(); auto depth_sz = static_cast<size_t>(depth.get_data_size()); int imu_sz = 0; rs2::frame accel_frame; rs2::frame gyro_frame; if(src->imu_on) { accel_frame = frame_set.first_or_default(RS2_STREAM_ACCEL); gyro_frame = frame_set.first_or_default(RS2_STREAM_GYRO); imu_sz = accel_frame.get_data_size() + gyro_frame.get_data_size(); } constexpr auto header_sz = sizeof(RSHeader); const auto buffer_sz = header_sz + color_sz + depth_sz + imu_sz + 1; buffer = gst_buffer_new_and_alloc(buffer_sz); if (buffer == nullptr) { GST_ELEMENT_ERROR (src, RESOURCE, FAILED, ("failed to allocate buffer"), (NULL)); throw new std::runtime_error("failed to allocate buffer"); } gst_buffer_map(buffer, &minfo, GST_MAP_WRITE); GST_LOG_OBJECT(src, "GstBuffer size=%lu, gst_stride=%d, frame_num=%llu", minfo.size, src->gst_stride, cframe.get_frame_number()); GST_LOG_OBJECT(src, "Buffer timestamp %f", cframe.get_timestamp()); std::memcpy(minfo.data, &header, sizeof(header)); // TODO refactor this section into cleaner code // NOTE We're always StreamMux now. If color or depth is off, then those portions will be 0 // if(src->stream_type == StreamType::StreamColor || src->stream_type == StreamType::StreamMux) // { int rs_stride = 0; auto outdata = minfo.data + sizeof(RSHeader); rs_stride = cframe.get_stride_in_bytes(); if (src->gst_stride == rs_stride) { std::memcpy(outdata, ((guint8 *)cframe.get_data()), color_sz); outdata += color_sz; } else { int i; GST_INFO_OBJECT(src, "Image strides not identical, copy will be slower."); for (i = 0; i < src->height; i++) { std::memcpy(outdata, ((guint8 *)cframe.get_data()) + i * rs_stride, rs_stride); outdata += src->gst_stride; } } if (depth_sz != 0) { std::memcpy(outdata, depth.get_data(), depth_sz); outdata += depth_sz; } if (imu_sz != 0 && src->imu_on) { #ifdef DEBUG auto print_imu = [](const float *ptr, const auto descrtion) { std::cout << descrtion << ": "; for (size_t idx = 0; idx < 3; ++idx) { std::cout << *ptr << ','; ++ptr; } std::cout << std::endl; }; print_imu(static_cast<const float*>(accel_frame.get_data()), "accel"); print_imu(static_cast<const float*>(gyro_frame.get_data()), "gyro"); #endif std::memcpy(outdata, accel_frame.get_data(), accel_frame.get_data_size()); outdata += accel_frame.get_data_size(); std::memcpy(outdata, gyro_frame.get_data(), gyro_frame.get_data_size()); outdata += gyro_frame.get_data_size(); } gst_buffer_unmap(buffer, &minfo); return buffer; } static buf_tuple demux(GstBuffer *buffer, const RSHeader &header) { GstMapInfo inmap, cmap, dmap, imumap; gst_buffer_map(buffer, &inmap, GST_MAP_READ); auto color_sz = header.color_height * header.color_stride; auto colorbuf = gst_buffer_new_and_alloc(color_sz); gst_buffer_map(colorbuf, &cmap, GST_MAP_WRITE); auto cdata = inmap.data + sizeof(RSHeader); std::memcpy(cmap.data, cdata, color_sz); auto depth_sz = header.depth_height * header.depth_stride; auto depthbuf = gst_buffer_new_and_alloc(depth_sz); gst_buffer_map(depthbuf, &dmap, GST_MAP_WRITE); auto ddata = cdata + color_sz; std::memcpy(dmap.data, ddata, depth_sz); GstBuffer* imubuf = nullptr; if (header.accel_format != GST_AUDIO_FORMAT_UNKNOWN && header.gyro_format != GST_AUDIO_FORMAT_UNKNOWN) { imubuf = gst_buffer_new_and_alloc(depth_sz); gst_buffer_map(imubuf, &imumap, GST_MAP_READ); constexpr auto imu_sz = 2*sizeof(rs2_vector); auto imudata = ddata + depth_sz; std::memcpy(imumap.data, imudata, imu_sz); GST_BUFFER_TIMESTAMP(imubuf) = GST_BUFFER_TIMESTAMP(buffer); gst_buffer_unmap(imubuf, &imumap); } GST_BUFFER_TIMESTAMP(colorbuf) = GST_BUFFER_TIMESTAMP(buffer); GST_BUFFER_TIMESTAMP(depthbuf) = GST_BUFFER_TIMESTAMP(buffer); gst_buffer_unmap(buffer, &inmap); gst_buffer_unmap(colorbuf, &cmap); gst_buffer_unmap(depthbuf, &dmap); return std::make_tuple(colorbuf, depthbuf, imubuf); } }; #endif // __GST_RS_MUX__
7,366
C++
.h
170
34.217647
110
0.603221
WKDSMRT/realsense-gstreamer
30
13
12
LGPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,490
gstrealsensesrc.h
WKDSMRT_realsense-gstreamer/src/gstrealsensesrc.h
/* GStreamer RealSense is a set of plugins to acquire frames from * Intel RealSense cameras into GStreamer pipeline. * Copyright (C) <2020> Tim Connelly/WKD.SMRT <timpconnelly@gmail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef __GST_REALSENSESRC_H__ #define __GST_REALSENSESRC_H__ #include <gst/gst.h> #include <gst/base/gstpushsrc.h> #include <gst/video/gstvideometa.h> #include <gst/video/gstvideopool.h> #include <librealsense2/rs.hpp> #include "common.hpp" G_BEGIN_DECLS /* #defines don't like whitespacey bits */ #define GST_TYPE_REALSENSESRC \ (gst_realsense_src_get_type()) #define GST_REALSENSESRC(obj) \ (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_REALSENSESRC,GstRealsenseSrc)) #define GST_REALSENSESRC_CLASS(klass) \ (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_REALSENSESRC,GstRealsenseSrcClass)) #define GST_IS_REALSENSESRC(obj) \ (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_REALSENSESRC)) #define GST_IS_REALSENSESRC_CLASS(klass) \ (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_REALSENSESRC)) typedef struct _GstRealsenseSrc GstRealsenseSrc; typedef struct _GstRealsenseSrcClass GstRealsenseSrcClass; using rs_pipe_ptr = std::unique_ptr<rs2::pipeline>; using rs_aligner_ptr = std::unique_ptr<rs2::align>; constexpr const auto DEFAULT_PROP_CAM_SN = 0; struct _GstRealsenseSrc { GstPushSrc element; GstVideoInfo info; /* protected by the object or stream lock */ gboolean silent; gboolean stop_requested = FALSE; GstCaps *caps; gint height; gint gst_stride; GstVideoFormat color_format = GST_VIDEO_FORMAT_UNKNOWN; GstVideoFormat depth_format = GST_VIDEO_FORMAT_UNKNOWN; GstAudioFormat accel_format = GST_AUDIO_FORMAT_UNKNOWN; GstAudioFormat gyro_format = GST_AUDIO_FORMAT_UNKNOWN; GstClockTime prev_time = 0; guint64 frame_count = 0; // Realsense vars rs_pipe_ptr rs_pipeline = nullptr; rs_aligner_ptr aligner = nullptr; bool has_imu = false; // Properties Align align = Align::None; guint64 serial_number = 0; StreamType stream_type = StreamType::StreamDepth; bool imu_on = true; }; struct _GstRealsenseSrcClass { GstPushSrcClass parent_class; }; GType gst_realsense_src_get_type (void); G_END_DECLS #endif /* __GST_REALSENSESRC_H__ */
2,939
C++
.h
76
36.394737
79
0.76601
WKDSMRT/realsense-gstreamer
30
13
12
LGPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,491
gstrealsensedemux.h
WKDSMRT_realsense-gstreamer/src/gstrealsensedemux.h
/* GStreamer RealSense is a set of plugins to acquire frames from * Intel RealSense cameras into GStreamer pipeline. * Copyright (C) <2020> Tim Connelly/WKD.SMRT <timpconnelly@gmail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef __GST_RSDEMUX_H__ #define __GST_RSDEMUX_H__ #include <gst/gst.h> #include "common.hpp" G_BEGIN_DECLS #define GST_TYPE_RSDEMUX \ (gst_rsdemux_get_type()) #define GST_RSDEMUX(obj) \ (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_RSDEMUX,GstRSDemux)) #define GST_RSDEMUX_CLASS(klass) \ (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_RSDEMUX,GstRSDemuxClass)) #define GST_IS_RSDEMUX(obj) \ (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_RSDEMUX)) #define GST_IS_RSDEMUX_CLASS(klass) \ (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_RSDEMUX)) typedef struct _GstRSDemux GstRSDemux; typedef struct _GstRSDemuxClass GstRSDemuxClass; struct _GstRSDemux { GstElement element; GstPad *sinkpad; GstPad *colorsrcpad = nullptr; GstPad *depthsrcpad = nullptr; GstPad *imusrcpad = nullptr; /* video params */ RSHeader header; gint in_height; gint in_width; gint in_stride_bytes; gint frame_count = 0; GstStateChange state_change = GST_STATE_CHANGE_NULL_TO_NULL; }; struct _GstRSDemuxClass { GstElementClass parent_class; }; GType gst_rsdemux_get_type (void); G_END_DECLS #endif /* __GST_RSDEMUX_H__ */
2,137
C++
.h
57
35.22807
70
0.730136
WKDSMRT/realsense-gstreamer
30
13
12
LGPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,492
common.hpp
WKDSMRT_realsense-gstreamer/src/common.hpp
/* GStreamer RealSense is a set of plugins to acquire frames from * Intel RealSense cameras into GStreamer pipeline. * Copyright (C) <2020> Tim Connelly/WKD.SMRT <timpconnelly@gmail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef __GST_RSCOMMON_H__ #define __GST_RSCOMMON_H__ enum StreamType { StreamColor, StreamDepth, StreamMux // Color and depth crammed into the same buffer }; enum Align { None, Color, Depth }; struct RSHeader { int color_height; int color_width; int color_stride; int color_format; int depth_height; int depth_width; int depth_stride; int depth_format; int accel_format; int gyro_format; bool operator!=(const RSHeader &rhs) { if (color_height != rhs.color_height) return true; if (color_width != rhs.color_width) return true; if (color_stride != rhs.color_stride) return true; if (color_format != rhs.color_format) return true; if (depth_height != rhs.depth_height) return true; if (depth_width != rhs.depth_width) return true; if (depth_stride != rhs.depth_stride) return true; if (depth_format != rhs.depth_format) return true; if (accel_format != rhs.accel_format) return true; if (gyro_format != rhs.gyro_format) return true; return false; } bool operator==(const RSHeader& rhs) { return !(*this != rhs); } }; #endif // __GST_RSCOMMON_H__
2,138
C++
.h
74
25.5
70
0.707483
WKDSMRT/realsense-gstreamer
30
13
12
LGPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,493
gstrealsensemeta.h
WKDSMRT_realsense-gstreamer/src/gstrealsensemeta.h
/* GStreamer RealSense is a set of plugins to acquire frames from * Intel RealSense cameras into GStreamer pipeline. * Copyright (C) <2020> Tim Connelly/WKD.SMRT <timpconnelly@gmail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef APP_CPP_GST_REALSENSE_META_H #define APP_CPP_GST_REALSENSE_META_H #include <gst/video/video.h> #include <librealsense2/rs.hpp> #include <string> G_BEGIN_DECLS struct _GstRealsenseMeta { GstMeta meta; uint exposure = 0; float depth_units = 0.f; rs2_intrinsics color_intrinsics; std::string* cam_model; std::string* cam_serial_number; std::string* json_descr; // generic json descriptor }; GType gst_realsense_meta_api_get_type (void); #define GST_REALSENSE_META_API_TYPE (gst_realsense_meta_api_get_type()) const GstMetaInfo *gst_realsense_meta_get_info (void); #define GST_REALSENSE_META_INFO (gst_realsense_meta_get_info()) typedef struct _GstRealsenseMeta GstRealsenseMeta; #define gst_buffer_get_realsense_meta(b) ((GstRealsenseMeta*)gst_buffer_get_meta((b),GST_REALSENSE_META_API_TYPE)) GstRealsenseMeta *gst_buffer_add_realsense_meta(GstBuffer* buffer, const std::string model, const std::string serial_number, uint exposure, const std::string json_descr, float depth_units, const rs2_intrinsics* color_intrinsics ); // for python access float gst_buffer_realsense_get_depth_meta(GstBuffer* buffer); rs2_intrinsics* gst_buffer_realsense_meta_get_instrinsics(GstBuffer* buffer); G_END_DECLS #endif //APP_CPP_GST_REALSENSE_META_H
2,276
C++
.h
53
39.924528
114
0.755324
WKDSMRT/realsense-gstreamer
30
13
12
LGPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,494
main.cpp
atom0s_ElgatoLegacy/ApiMsWinCoreVersion110/main.cpp
/** * ElgatoLegacy - Copyright (c) 2020 atom0s * Contact: https://atom0s.com * * This file is part of ElgatoLegacy. * * ElgatoLegacy is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ElgatoLegacy is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ElgatoLegacy. If not, see <https://www.gnu.org/licenses/>. */ #pragma comment(lib, "Version.lib") #pragma comment(lib, "WtsApi32.lib") #include <Windows.h> #include <string> #include <WtsApi32.h> #pragma comment(lib, "../thirdparty/detours.lib") #include "../thirdparty/detours.h" #ifndef STATUS_SUCCESS #define STATUS_SUCCESS 0x00000000 #endif /** * GetFileVersionInfoW proxy. * * WinVer: Windows 2000 */ BOOL __stdcall expGetFileVersionInfoW(LPCWSTR lptstrFilename, DWORD dwHandle, DWORD dwLen, LPVOID lpData) { // Forward call to Version.dll function.. return ::GetFileVersionInfoW(lptstrFilename, dwHandle, dwLen, lpData); } /** * GetFileVersionInfoSizeW proxy. * * WinVer: Windows 2000 */ DWORD __stdcall expGetFileVersionInfoSizeW(LPCWSTR lptstrFilename, LPDWORD lpdwHandle) { // Forward call to Version.dll function.. return ::GetFileVersionInfoSizeW(lptstrFilename, lpdwHandle); } /** * GetFileVersionInfoExW proxy. * * WinVer: Windows Vista */ BOOL __stdcall expGetFileVersionInfoExW(DWORD dwFlags, LPCWSTR lpwstrFilename, DWORD dwHandle, DWORD dwLen, LPVOID lpData) { // Forward call to Version.dll function.. return ::GetFileVersionInfoExW(dwFlags, lpwstrFilename, dwHandle, dwLen, lpData); } /** * GetFileVersionInfoSizeExW proxy. * * WinVer: Windows Vista */ DWORD __stdcall expGetFileVersionInfoSizeExW(DWORD dwFlags, LPCWSTR lpwstrFileName, LPDWORD lpdwHandle) { // Forward call to Version.dll function.. return ::GetFileVersionInfoSizeExW(dwFlags, lpwstrFileName, lpdwHandle); } /** * VerFindFileW proxy. * * WinVer: Windows 2000 */ DWORD __stdcall expVerFindFileW(DWORD uFlags, LPCWSTR szFileName, LPCWSTR szWinDir, LPCWSTR szAppDir, LPWSTR szCurDir, PUINT puCurDirLen, LPWSTR szDestDir, PUINT puDestDirLen) { // Forward call to Version.dll function.. return ::VerFindFileW(uFlags, szFileName, szWinDir, szAppDir, szCurDir, puCurDirLen, szDestDir, puDestDirLen); } /** * VerQueryValueW proxy. * * WinVer: Windows 2000 */ BOOL __stdcall expVerQueryValueW(LPCVOID pBlock, LPCWSTR lpSubBlock, LPVOID* lplpBuffer, PUINT puLen) { // Forward call to Version.dll function.. return ::VerQueryValueW(pBlock, lpSubBlock, lplpBuffer, puLen); } /** * Detour Prototypes */ extern "C" { // Windows 7 Related Hooks auto Real_WTSQuerySessionInformationW = static_cast<decltype(::WTSQuerySessionInformationW)*>(::WTSQuerySessionInformationW); auto Real_GetProcAddress = static_cast<decltype(::GetProcAddress)*>(::GetProcAddress); // Plugin List Bypass Windows Version Check NTSTATUS /**/ (NTAPI* Real_RtlGetVersion)(PRTL_OSVERSIONINFOW lpVersionInformation) = nullptr; }; /** * kernel32!GetProcAddress detour callback. * * @param {HMODULE} hModule - A handle to the DLL module that contains the function or variable. * @param {LPCSTR} lpProcName - The function or variable name, or the function's ordinal value. * @return {BOOL} The address of the exported function on success, NULL otherwise. */ FARPROC __stdcall Mine_GetProcAddress(HMODULE hModule, LPCSTR lpProcName) { if (lpProcName != nullptr && (uint64_t)lpProcName > 0xFFFF) { // Redirect platform role lookups to the Windows 7 supported API.. if (_strnicmp(lpProcName, u8"PowerDeterminePlatformRoleEx", 28) == 0) return Real_GetProcAddress(hModule, u8"PowerDeterminePlatformRole"); } return Real_GetProcAddress(hModule, lpProcName); } /** * wtsapi32!WTSQuerySessionInformationW detour callback. * * @param {HANDLE} hServer - A handle to an RD Session Host server. * @param {DWORD} SessionId - A Remote Desktop Services session identifier. * @param {WTS_INFO_CLASS} WTSInfoClass - A value of the WTS_INFO_CLASS enumeration that indicates the type of session information to retrieve in a call to the WTSQuerySessionInformation function. * @param {LPWSTR} ppBuffer - A pointer to a variable that receives a pointer to the requested information. * @param {DWORD*} pBytesReturned - A pointer to a variable that receives the size, in bytes, of the data returned in ppBuffer. * @return {BOOL} Non-zero on success, FALSE otherwise. */ BOOL __stdcall Mine_WTSQuerySessionInformationW(HANDLE hServer, DWORD SessionId, WTS_INFO_CLASS WTSInfoClass, LPWSTR* ppBuffer, DWORD* pBytesReturned) { // Allow the actual call to happen.. const auto ret = Real_WTSQuerySessionInformationW(hServer, SessionId, WTSInfoClass, ppBuffer, pBytesReturned); if (!ret) return ret; // Check for session info lookups.. if (WTSInfoClass == WTS_INFO_CLASS::WTSSessionInfoEx) { // Obtain the session information data.. const auto session = (WTSINFOEXW*)*ppBuffer; // Force the unlock state of the session.. session->Data.WTSInfoExLevel1.SessionFlags = WTS_SESSIONSTATE_UNLOCK; } return ret; } /** * ntdll!RtlGetVersion detour callback. * * @param {PRTL_OSVERSIONINFOW} lpVersionInformation - Pointer to either a RTL_OSVERSIONINFOW structure or a RTL_OSVERSIONINFOEXW structure that contains the version information about the currently running operating system. * @return {NTSTATUS} STATUS_SUCCESS on success. */ NTSTATUS NTAPI Mine_RtlGetVersion(PRTL_OSVERSIONINFOW lpVersionInformation) { const auto res = Real_RtlGetVersion(lpVersionInformation); if (res == STATUS_SUCCESS) { // Fake the return as Windows 10 (1909 - 18363.592) lpVersionInformation->dwMajorVersion = 0x0A; lpVersionInformation->dwMinorVersion = 0x00; lpVersionInformation->dwBuildNumber = 0x47BB; lpVersionInformation->dwPlatformId = 0x02; } return res; } /** * Applies detours to functions that we patch to allow various fixes/features to work. */ void __stdcall ApplyDetours(void) { // Obtain the RtlGetVersion function address.. auto ntdll = ::GetModuleHandleA(u8"ntdll.dll"); if (ntdll != nullptr) Real_RtlGetVersion = (decltype(Real_RtlGetVersion))::GetProcAddress(ntdll, u8"RtlGetVersion"); ::DetourTransactionBegin(); ::DetourUpdateThread(::GetCurrentThread()); // Windows 7 Related Hooks ::DetourAttach(&(PVOID&)Real_GetProcAddress, Mine_GetProcAddress); ::DetourAttach(&(PVOID&)Real_WTSQuerySessionInformationW, Mine_WTSQuerySessionInformationW); // Plugin List Bypass Windows Version Check if (Real_RtlGetVersion != nullptr) ::DetourAttach(&(PVOID&)Real_RtlGetVersion, Mine_RtlGetVersion); ::DetourTransactionCommit(); } /** * Module entry point. * * @param {HINSTANCE} hInstDLL - The module instance handle. * @param {DWORD} fdwReason - The reason this entry point was invoked. * @param {LPVOID} lpvReserved - System reserved. * @return {BOOL} TRUE on success, FALSE otherwise. */ BOOL APIENTRY DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID lpReserved) { switch (fdwReason) { case DLL_PROCESS_ATTACH: ::DisableThreadLibraryCalls(hInstDLL); ApplyDetours(); return TRUE; default: break; } return TRUE; }
7,812
C++
.cpp
202
35.252475
223
0.743968
atom0s/ElgatoLegacy
30
4
9
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,495
main.cpp
atom0s_ElgatoLegacy/ApiMsWinCoreVersion111/main.cpp
/** * ElgatoLegacy - Copyright (c) 2020 atom0s * Contact: https://atom0s.com * * This file is part of ElgatoLegacy. * * ElgatoLegacy is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ElgatoLegacy is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ElgatoLegacy. If not, see <https://www.gnu.org/licenses/>. */ #pragma comment(lib, "Version.lib") #include <Windows.h> #pragma comment(lib, "../thirdparty/detours.lib") #include "../thirdparty/detours.h" #ifndef STATUS_SUCCESS #define STATUS_SUCCESS 0x00000000 #endif /** * GetFileVersionInfoW proxy. * * WinVer: Windows 2000 */ BOOL __stdcall expGetFileVersionInfoW(LPCWSTR lptstrFilename, DWORD dwHandle, DWORD dwLen, LPVOID lpData) { // Forward call to Version.dll function.. return ::GetFileVersionInfoW(lptstrFilename, dwHandle, dwLen, lpData); } /** * GetFileVersionInfoSizeW proxy. * * WinVer: Windows 2000 */ DWORD __stdcall expGetFileVersionInfoSizeW(LPCWSTR lptstrFilename, LPDWORD lpdwHandle) { // Forward call to Version.dll function.. return ::GetFileVersionInfoSizeW(lptstrFilename, lpdwHandle); } /** * GetFileVersionInfoExW proxy. * * WinVer: Windows Vista */ BOOL __stdcall expGetFileVersionInfoExW(DWORD dwFlags, LPCWSTR lpwstrFilename, DWORD dwHandle, DWORD dwLen, LPVOID lpData) { // Forward call to Version.dll function.. return ::GetFileVersionInfoExW(dwFlags, lpwstrFilename, dwHandle, dwLen, lpData); } /** * GetFileVersionInfoSizeExW proxy. * * WinVer: Windows Vista */ DWORD __stdcall expGetFileVersionInfoSizeExW(DWORD dwFlags, LPCWSTR lpwstrFileName, LPDWORD lpdwHandle) { // Forward call to Version.dll function.. return ::GetFileVersionInfoSizeExW(dwFlags, lpwstrFileName, lpdwHandle); } /** * VerFindFileW proxy. * * WinVer: Windows 2000 */ DWORD __stdcall expVerFindFileW(DWORD uFlags, LPCWSTR szFileName, LPCWSTR szWinDir, LPCWSTR szAppDir, LPWSTR szCurDir, PUINT puCurDirLen, LPWSTR szDestDir, PUINT puDestDirLen) { // Forward call to Version.dll function.. return ::VerFindFileW(uFlags, szFileName, szWinDir, szAppDir, szCurDir, puCurDirLen, szDestDir, puDestDirLen); } /** * VerQueryValueW proxy. * * WinVer: Windows 2000 */ BOOL __stdcall expVerQueryValueW(LPCVOID pBlock, LPCWSTR lpSubBlock, LPVOID* lplpBuffer, PUINT puLen) { // Forward call to Version.dll function.. return ::VerQueryValueW(pBlock, lpSubBlock, lplpBuffer, puLen); } /** * Detour Prototypes */ extern "C" { // Plugin List Bypass Windows Version Check NTSTATUS /**/ (NTAPI* Real_RtlGetVersion)(PRTL_OSVERSIONINFOW lpVersionInformation) = nullptr; }; /** * ntdll!RtlGetVersion detour callback. * * @param {PRTL_OSVERSIONINFOW} lpVersionInformation - Pointer to either a RTL_OSVERSIONINFOW structure or a RTL_OSVERSIONINFOEXW structure that contains the version information about the currently running operating system. * @return {NTSTATUS} STATUS_SUCCESS on success. */ NTSTATUS NTAPI Mine_RtlGetVersion(PRTL_OSVERSIONINFOW lpVersionInformation) { const auto res = Real_RtlGetVersion(lpVersionInformation); if (res == STATUS_SUCCESS) { // Fake the return as Windows 10 (1909 - 18363.592) lpVersionInformation->dwMajorVersion = 0x0A; lpVersionInformation->dwMinorVersion = 0x00; lpVersionInformation->dwBuildNumber = 0x47BB; lpVersionInformation->dwPlatformId = 0x02; } return res; } /** * Applies detours to functions that we patch to allow various fixes/features to work. */ void __stdcall ApplyDetours(void) { // Obtain the RtlGetVersion function address.. auto ntdll = ::GetModuleHandleA(u8"ntdll.dll"); if (ntdll != nullptr) Real_RtlGetVersion = (decltype(Real_RtlGetVersion))::GetProcAddress(ntdll, u8"RtlGetVersion"); ::DetourTransactionBegin(); ::DetourUpdateThread(::GetCurrentThread()); // Plugin List Bypass Windows Version Check if (Real_RtlGetVersion != nullptr) ::DetourAttach(&(PVOID&)Real_RtlGetVersion, Mine_RtlGetVersion); ::DetourTransactionCommit(); } /** * Module entry point. * * @param {HINSTANCE} hInstDLL - The module instance handle. * @param {DWORD} fdwReason - The reason this entry point was invoked. * @param {LPVOID} lpvReserved - System reserved. * @return {BOOL} TRUE on success, FALSE otherwise. */ BOOL APIENTRY DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID lpReserved) { switch (fdwReason) { case DLL_PROCESS_ATTACH: ::DisableThreadLibraryCalls(hInstDLL); ApplyDetours(); return TRUE; default: break; } return TRUE; }
5,086
C++
.cpp
150
30.733333
223
0.744664
atom0s/ElgatoLegacy
30
4
9
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,496
main.cpp
atom0s_ElgatoLegacy/ApiMsWinSHCoreScaling111/main.cpp
/** * ElgatoLegacy - Copyright (c) 2020 atom0s * Contact: https://atom0s.com * * This file is part of ElgatoLegacy. * * ElgatoLegacy is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ElgatoLegacy is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ElgatoLegacy. If not, see <https://www.gnu.org/licenses/>. */ #include <Windows.h> /** * Device Scale Factor Enumeration */ enum DEVICE_SCALE_FACTOR { DEVICE_SCALE_FACTOR_INVALID, SCALE_100_PERCENT, SCALE_120_PERCENT, SCALE_125_PERCENT, SCALE_140_PERCENT, SCALE_150_PERCENT, SCALE_160_PERCENT, SCALE_175_PERCENT, SCALE_180_PERCENT, SCALE_200_PERCENT, SCALE_225_PERCENT, SCALE_250_PERCENT, SCALE_300_PERCENT, SCALE_350_PERCENT, SCALE_400_PERCENT, SCALE_450_PERCENT, SCALE_500_PERCENT }; /** * Display Device Type Enumeration */ enum DISPLAY_DEVICE_TYPE { DEVICE_PRIMARY, DEVICE_IMMERSIVE }; /** * Monitor DPI Type Enumeration */ enum MONITOR_DPI_TYPE { MDT_EFFECTIVE_DPI, MDT_ANGULAR_DPI, MDT_RAW_DPI, MDT_DEFAULT }; /** * Process DPI Awareness Enumeration */ enum PROCESS_DPI_AWARENESS { PROCESS_DPI_UNAWARE, PROCESS_SYSTEM_DPI_AWARE, PROCESS_PER_MONITOR_DPI_AWARE }; /** * GetDpiForMonitor proxy. * * WinVer: Windows 8.1 */ HRESULT expGetDpiForMonitor(HMONITOR hmonitor, MONITOR_DPI_TYPE dpiType, UINT* dpiX, UINT* dpiY) { UNREFERENCED_PARAMETER(hmonitor); // Return known valid values.. (3440 x 1440) switch (dpiType) { case MDT_ANGULAR_DPI: *dpiX = 108; *dpiY = 108; break; case MDT_RAW_DPI: *dpiX = 109; *dpiY = 109; break; case MDT_EFFECTIVE_DPI: case MDT_DEFAULT: *dpiX = 96; *dpiY = 96; break; } return S_OK; } /** * GetProcessDpiAwareness proxy. * * WinVer: Windows 8.1 */ HRESULT expGetProcessDpiAwareness(HANDLE hprocess, PROCESS_DPI_AWARENESS* value) { UNREFERENCED_PARAMETER(hprocess); // Assume process is DPI unaware.. *value = PROCESS_DPI_UNAWARE; return S_OK; } /** * GetScaleFactorForDevice proxy. * * WinVer: Windows 8 */ DEVICE_SCALE_FACTOR expGetScaleFactorForDevice(DISPLAY_DEVICE_TYPE deviceType) { UNREFERENCED_PARAMETER(deviceType); // Use the default scale factor as the return.. return SCALE_100_PERCENT; } /** * GetScaleFactorForMonitor proxy. * * WinVer: Windows 8.1 */ HRESULT expGetScaleFactorForMonitor(HMONITOR hMon, DEVICE_SCALE_FACTOR* pScale) { UNREFERENCED_PARAMETER(hMon); // Use the default scale factor as the return.. *pScale = SCALE_100_PERCENT; return S_OK; } /** * RegisterScaleChangeEvent proxy. * * WinVer: Windows 8.1 */ HRESULT expRegisterScaleChangeEvent(HANDLE hEvent, DWORD_PTR* pdwCookie) { UNREFERENCED_PARAMETER(hEvent); UNREFERENCED_PARAMETER(pdwCookie); return S_OK; } /** * RegisterScaleChangeNotifications proxy. * * WinVer: Windows 8 */ HRESULT expRegisterScaleChangeNotifications(DISPLAY_DEVICE_TYPE displayDevice, HWND hwndNotify, UINT uMsgNotify, DWORD* pdwCookie) { UNREFERENCED_PARAMETER(displayDevice); UNREFERENCED_PARAMETER(hwndNotify); UNREFERENCED_PARAMETER(uMsgNotify); UNREFERENCED_PARAMETER(pdwCookie); return S_OK; } /** * RevokeScaleChangeNotifications proxy. * * WinVer: Windows 8 */ HRESULT expRevokeScaleChangeNotifications(DISPLAY_DEVICE_TYPE displayDevice, DWORD dwCookie) { UNREFERENCED_PARAMETER(displayDevice); UNREFERENCED_PARAMETER(dwCookie); return S_OK; } /** * SetProcessDpiAwareness proxy. * * WinVer: Windows 8.1 */ HRESULT __stdcall expSetProcessDpiAwareness(PROCESS_DPI_AWARENESS value) { UNREFERENCED_PARAMETER(value); return S_OK; } /** * UnregisterScaleChangeEvent proxy. * * WinVer: Windows 8.1 */ HRESULT expUnregisterScaleChangeEvent(DWORD_PTR dwCookie) { UNREFERENCED_PARAMETER(dwCookie); return S_OK; } /** * Module entry point. * * @param {HINSTANCE} hInstDLL - The module instance handle. * @param {DWORD} fdwReason - The reason this entry point was invoked. * @param {LPVOID} lpvReserved - System reserved. * @return {BOOL} TRUE on success, FALSE otherwise. */ BOOL APIENTRY DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID lpvReserved) { UNREFERENCED_PARAMETER(lpvReserved); switch (fdwReason) { case DLL_PROCESS_ATTACH: ::DisableThreadLibraryCalls(hInstDLL); return TRUE; default: break; } return TRUE; }
5,056
C++
.cpp
208
20.658654
130
0.712448
atom0s/ElgatoLegacy
30
4
9
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,498
fts-backend-flatcurve-xapian.cpp
slusarz_dovecot-fts-flatcurve/src/fts-backend-flatcurve-xapian.cpp
/* Copyright (c) Michael Slusarz <slusarz@curecanti.org> * See the included COPYING file */ #ifdef XAPIAN_MOVE_SEMANTICS # define std_move(x) std::move(x) #else # define std_move(x) x #endif #include <xapian.h> #include <algorithm> #include <sstream> #include <string> #include "fts-flatcurve-config.h" extern "C" { #include "lib.h" #include "array.h" #include "file-create-locked.h" #include "hash.h" #include "hex-binary.h" #include "mail-storage-private.h" #include "mail-search.h" #include "md5.h" #include "sleep.h" #include "str.h" #include "time-util.h" #include "unichar.h" #include "fts-backend-flatcurve.h" #include "fts-backend-flatcurve-xapian.h" #include <dirent.h> #include <stdio.h> }; /* How Xapian DBs work in fts-flatcurve: all data lives in under one * per-mailbox directory (FTS_FLATCURVE_LABEL) stored at the root of the * mailbox indexes directory. * * There are two different permanent data types within that library: * - "index.###": The actual Xapian DB shards. Combined, this comprises the * FTS data for the mailbox. These shards may be directly written to, but * only when deleting messages - new messages are never stored directly to * this DB. Additionally, these DBs are never directly queried; a dummy * object is used to indirectly query them. These indexes may occasionally * be combined into a single index via optimization processes. * - "current.###": Xapian DB that contains the index shard where new messages * are stored. Once this index reaches certain (configurable) limits, a new * shard is created and rotated in as the new current index by creating * a shard with a suffix higher than the previous current DB. * * Within a session, we create a dummy Xapian::Database object, scan the data * directory for all indexes, and add each of them to the dummy object. For * queries, we then just need to query the dummy object and Xapian handles * everything for us. Writes need to be handled separately, as a * WritableDatabase object only supports a single on-disk DB at a time; a DB * shard, whether "index" or "current", must be directly written to in order * to modify. * * Data storage: Xapian does not support substring searches by default, so * (if substring searching is enabled) we instead need to explicitly store all * substrings of the string, up to the point where the substring becomes * smaller than min_term_size. */ #define FLATCURVE_XAPIAN_DB_PREFIX "index." #define FLATCURVE_XAPIAN_DB_CURRENT_PREFIX "current." /* These are temporary data types that may appear in the fts directory. They * are not intended to perservere between sessions. */ #define FLATCURVE_XAPIAN_DB_OPTIMIZE "optimize" /* Xapian "recommendations" are that you begin your local prefix identifier * with "X" for data that doesn't match with a data type listed as a Xapian * "convention". However, this recommendation is for maintaining * compatability with the search front-end (Omega) that they provide. We don't * care about compatability, so save storage space by using single letter * prefixes. Bodytext is stored without prefixes, as it is expected to be the * single largest storage pool. */ #define FLATCURVE_XAPIAN_ALL_HEADERS_PREFIX "A" #define FLATCURVE_XAPIAN_BOOLEAN_FIELD_PREFIX "B" #define FLATCURVE_XAPIAN_HEADER_PREFIX "H" #define FLATCURVE_XAPIAN_ALL_HEADERS_QP "allhdrs" #define FLATCURVE_XAPIAN_HEADER_BOOL_QP "hdr_bool" #define FLATCURVE_XAPIAN_HEADER_QP "hdr_" #define FLATCURVE_XAPIAN_BODY_QP "body" /* Version database, so that any schema changes can be caught. */ #define FLATCURVE_XAPIAN_DB_KEY_PREFIX "dovecot." #define FLATCURVE_XAPIAN_DB_VERSION_KEY FLATCURVE_XAPIAN_DB_KEY_PREFIX \ FTS_FLATCURVE_LABEL #define FLATCURVE_XAPIAN_DB_VERSION 1 #define FLATCURVE_DBW_LOCK_RETRY_SECS 1 #define FLATCURVE_DBW_LOCK_RETRY_MAX 60 #define FLATCURVE_MANUAL_OPTIMIZE_COMMIT_LIMIT 500 /* Dotlock: needed to ensure we don't run into race conditions when * manipulating current directory. */ #define FLATCURVE_XAPIAN_LOCK_FNAME "flatcurve-lock" #define FLATCURVE_XAPIAN_LOCK_TIMEOUT_SECS 5 #define ENUM_EMPTY(x) ((enum x) 0) struct flatcurve_xapian_db_path { const char *fname; const char *path; }; enum flatcurve_xapian_db_type { FLATCURVE_XAPIAN_DB_TYPE_INDEX, FLATCURVE_XAPIAN_DB_TYPE_CURRENT, FLATCURVE_XAPIAN_DB_TYPE_OPTIMIZE, FLATCURVE_XAPIAN_DB_TYPE_LOCK, FLATCURVE_XAPIAN_DB_TYPE_UNKNOWN }; struct flatcurve_xapian_db { Xapian::Database *db; Xapian::WritableDatabase *dbw; struct flatcurve_xapian_db_path *dbpath; unsigned int changes; enum flatcurve_xapian_db_type type; }; HASH_TABLE_DEFINE_TYPE(xapian_db, char *, struct flatcurve_xapian_db *); struct flatcurve_xapian { /* Current database objects. */ struct flatcurve_xapian_db *dbw_current; Xapian::Database *db_read; HASH_TABLE_TYPE(xapian_db) dbs; unsigned int shards; /* Locking for current shard manipulation. */ struct file_lock *lock; const char *lock_path; /* Xapian pool: used for per mailbox DB info, so it can be easily * cleared when switching mailboxes. Not for use with long * lived data (e.g. optimize). */ pool_t pool; /* Current document. */ Xapian::Document *doc; uint32_t doc_uid; unsigned int doc_updates; bool doc_created:1; /* List of mailboxes to optimize at shutdown. */ HASH_TABLE(char *, char *) optimize; bool deinit:1; bool closing:1; }; struct flatcurve_fts_query_xapian_maybe { Xapian::Query *query; }; struct flatcurve_fts_query_xapian { Xapian::Query *query; ARRAY(struct flatcurve_fts_query_xapian_maybe) maybe_queries; bool and_search:1; bool maybe:1; bool start:1; }; struct flatcurve_xapian_db_iter { struct flatcurve_fts_backend *backend; DIR *dirp; /* These are set every time next() is run. */ struct flatcurve_xapian_db_path *path; enum flatcurve_xapian_db_type type; }; enum flatcurve_xapian_db_opts { FLATCURVE_XAPIAN_DB_NOCREATE_CURRENT = BIT(0), FLATCURVE_XAPIAN_DB_IGNORE_EMPTY = BIT(1), FLATCURVE_XAPIAN_DB_NOCLOSE_CURRENT = BIT(2) }; enum flatcurve_xapian_wdb { FLATCURVE_XAPIAN_WDB_CREATE = BIT(0) }; enum flatcurve_xapian_db_close { FLATCURVE_XAPIAN_DB_CLOSE_WDB_COMMIT = BIT(0), FLATCURVE_XAPIAN_DB_CLOSE_WDB = BIT(1), FLATCURVE_XAPIAN_DB_CLOSE_DB = BIT(2), FLATCURVE_XAPIAN_DB_CLOSE_ROTATE = BIT(3), FLATCURVE_XAPIAN_DB_CLOSE_MBOX = BIT(4) }; /* Externally accessible struct. */ struct fts_flatcurve_xapian_query_iter { struct flatcurve_fts_backend *backend; struct flatcurve_fts_query *query; Xapian::Database *db; Xapian::Enquire *enquire; Xapian::MSetIterator i; Xapian::MSet m; struct fts_flatcurve_xapian_query_result *result; bool init:1; bool main_query:1; }; static void fts_flatcurve_xapian_check_db_version(struct flatcurve_fts_backend *backend, struct flatcurve_xapian_db *xdb); static void fts_flatcurve_xapian_close_db(struct flatcurve_fts_backend *backend, struct flatcurve_xapian_db *xdb, enum flatcurve_xapian_db_close opts); static void fts_flatcurve_xapian_close_dbs(struct flatcurve_fts_backend *backend, enum flatcurve_xapian_db_close opts); static bool fts_flatcurve_xapian_db_populate(struct flatcurve_fts_backend *backend, enum flatcurve_xapian_db_opts opts); void fts_flatcurve_xapian_init(struct flatcurve_fts_backend *backend) { backend->xapian = p_new(backend->pool, struct flatcurve_xapian, 1); backend->xapian->pool = pool_alloconly_create(FTS_FLATCURVE_LABEL " xapian", 2048); hash_table_create(&backend->xapian->dbs, backend->xapian->pool, 4, str_hash, strcmp); } void fts_flatcurve_xapian_deinit(struct flatcurve_fts_backend *backend) { struct hash_iterate_context *iter; void *key, *val; struct flatcurve_xapian *x = backend->xapian; x->deinit = TRUE; if (hash_table_is_created(x->optimize)) { iter = hash_table_iterate_init(x->optimize); while (hash_table_iterate(iter, x->optimize, &key, &val)) { str_append(backend->boxname, (const char *)key); str_append(backend->db_path, (const char *)val); fts_flatcurve_xapian_optimize_box(backend); } hash_table_iterate_deinit(&iter); hash_table_destroy(&x->optimize); } hash_table_destroy(&x->dbs); pool_unref(&x->pool); x->deinit = FALSE; } static struct flatcurve_xapian_db_path * fts_flatcurve_xapian_create_db_path(struct flatcurve_fts_backend *backend, const char *fname) { struct flatcurve_xapian_db_path *dbpath; dbpath = p_new(backend->xapian->pool, struct flatcurve_xapian_db_path, 1); dbpath->fname = p_strdup(backend->xapian->pool, fname); dbpath->path = p_strdup_printf(backend->xapian->pool, "%s%s", str_c(backend->db_path), fname); return dbpath; } // dbpath = NULL: delete the entire flatcurve index static void fts_flatcurve_xapian_delete(struct flatcurve_fts_backend *backend, struct flatcurve_xapian_db_path *dbpath) { (void)fts_backend_flatcurve_delete_dir( backend, (dbpath == NULL) ? str_c(backend->db_path) : dbpath->path); } static struct flatcurve_xapian_db_iter * fts_flatcurve_xapian_db_iter_init(struct flatcurve_fts_backend *backend, enum flatcurve_xapian_db_opts opts) { DIR *dirp; struct flatcurve_xapian_db_iter *iter; dirp = opendir(str_c(backend->db_path)); if ((dirp == NULL) && HAS_NO_BITS(opts, FLATCURVE_XAPIAN_DB_NOCREATE_CURRENT)) { e_debug(backend->event, "Cannot open DB (RO); opendir(%s) " "failed: %m", str_c(backend->db_path)); return NULL; } iter = p_new(backend->xapian->pool, struct flatcurve_xapian_db_iter, 1); iter->backend = backend; iter->dirp = dirp; return iter; } static bool fts_flatcurve_xapian_db_iter_next(struct flatcurve_xapian_db_iter *iter) { struct dirent *d; struct stat st; if ((iter->dirp == NULL) || (d = readdir(iter->dirp)) == NULL) return FALSE; if ((strcmp(d->d_name, ".") == 0) || (strcmp(d->d_name, "..") == 0)) return fts_flatcurve_xapian_db_iter_next(iter); iter->path = fts_flatcurve_xapian_create_db_path(iter->backend, d->d_name); iter->type = FLATCURVE_XAPIAN_DB_TYPE_UNKNOWN; if (str_begins(d->d_name, FLATCURVE_XAPIAN_DB_PREFIX)) { if ((stat(iter->path->path, &st) >= 0) && S_ISDIR(st.st_mode)) iter->type = FLATCURVE_XAPIAN_DB_TYPE_INDEX; } else if (str_begins(d->d_name, FLATCURVE_XAPIAN_DB_CURRENT_PREFIX)) { if ((stat(iter->path->path, &st) >= 0) && S_ISDIR(st.st_mode)) iter->type = FLATCURVE_XAPIAN_DB_TYPE_CURRENT; } else if (str_begins(d->d_name, FLATCURVE_XAPIAN_LOCK_FNAME)) { iter->type = FLATCURVE_XAPIAN_DB_TYPE_LOCK; } else if (strcmp(d->d_name, FLATCURVE_XAPIAN_DB_OPTIMIZE) == 0) { if ((stat(iter->path->path, &st) >= 0) && S_ISDIR(st.st_mode)) iter->type = FLATCURVE_XAPIAN_DB_TYPE_OPTIMIZE; } return TRUE; } static void fts_flatcurve_xapian_db_iter_deinit(struct flatcurve_xapian_db_iter **_iter) { struct flatcurve_xapian_db_iter *iter = *_iter; *_iter = NULL; if (iter->dirp != NULL) (void)closedir(iter->dirp); p_free(iter->backend->xapian->pool, iter); } // throws Exception on error static struct flatcurve_xapian_db * fts_flatcurve_xapian_write_db_get_do(struct flatcurve_fts_backend *backend, struct flatcurve_xapian_db *xdb, int db_flags) { enum flatcurve_xapian_db_opts opts = FLATCURVE_XAPIAN_DB_NOCLOSE_CURRENT; unsigned int wait = 0; while (xdb->dbw == NULL) { try { xdb->dbw = new Xapian::WritableDatabase( xdb->dbpath->path, db_flags); } catch (Xapian::DatabaseLockError &e) { e_debug(backend->event, "Waiting for DB (RW; %s) lock", xdb->dbpath->fname); wait += FLATCURVE_DBW_LOCK_RETRY_SECS; if (wait > FLATCURVE_DBW_LOCK_RETRY_MAX) i_fatal(FTS_FLATCURVE_DEBUG_PREFIX "Could not " "obtain DB lock (RW; %s)", xdb->dbpath->fname); i_sleep_intr_secs(FLATCURVE_DBW_LOCK_RETRY_SECS); } } return xdb; } static struct flatcurve_xapian_db * fts_flatcurve_xapian_write_db_get(struct flatcurve_fts_backend *backend, struct flatcurve_xapian_db *xdb, enum flatcurve_xapian_wdb wopts) { int db_flags; if (xdb->dbw != NULL) return xdb; db_flags = (HAS_ALL_BITS(wopts, FLATCURVE_XAPIAN_WDB_CREATE) ? Xapian::DB_CREATE_OR_OPEN : Xapian::DB_OPEN) | Xapian::DB_NO_SYNC; try { fts_flatcurve_xapian_write_db_get_do(backend, xdb, db_flags); } catch (Xapian::Error &e) { e_debug(backend->event, "Cannot open DB (RW; %s); %s", xdb->dbpath->fname, e.get_description().c_str()); return NULL; } if (xdb->type == FLATCURVE_XAPIAN_DB_TYPE_CURRENT) fts_flatcurve_xapian_check_db_version(backend, xdb); e_debug(backend->event, "Opened DB (RW; %s) messages=%u version=%u", xdb->dbpath->fname, xdb->dbw->get_doccount(), FLATCURVE_XAPIAN_DB_VERSION); return xdb; } static struct flatcurve_xapian_db_path * fts_flatcurve_xapian_rename_db(struct flatcurve_fts_backend *backend, struct flatcurve_xapian_db_path *path) { unsigned int i; struct flatcurve_xapian_db_path *newpath; bool retry = FALSE; for (i = 0; i < 3; ++i) { std::ostringstream ss; std::string new_fname(FLATCURVE_XAPIAN_DB_PREFIX); ss << i_rand_limit(8192); new_fname += ss.str(); newpath = fts_flatcurve_xapian_create_db_path( backend, new_fname.c_str()); if (rename(path->path, newpath->path) < 0) { if (retry || (errno != ENOTEMPTY) && (errno != EEXIST)) { p_free(backend->xapian->pool, newpath); return NULL; } /* Looks like a naming conflict; try once again with * a different filename. ss will have additional * randomness added to the original suffix, so it * will almost certainly work the second time. */ retry = TRUE; } else { return newpath; } } /* If we still haven't found a valid filename, something is very * wrong. Exit before we enter an infinite loop and consume all the * memory. */ i_unreached(); } static bool fts_flatcurve_xapian_need_optimize(struct flatcurve_fts_backend *backend) { struct flatcurve_xapian *x = backend->xapian; return ((backend->fuser->set.optimize_limit > 0) && (x->shards >= backend->fuser->set.optimize_limit)); } static void fts_flatcurve_xapian_optimize_mailbox(struct flatcurve_fts_backend *backend) { struct flatcurve_xapian *x = backend->xapian; if (x->deinit || !fts_flatcurve_xapian_need_optimize(backend)) return; if (!hash_table_is_created(x->optimize)) hash_table_create(&x->optimize, backend->pool, 0, str_hash, strcmp); if (hash_table_lookup(x->optimize, str_c(backend->boxname)) == NULL) hash_table_insert(x->optimize, p_strdup(backend->pool, str_c(backend->boxname)), p_strdup(backend->pool, str_c(backend->db_path))); } static struct flatcurve_xapian_db * fts_flatcurve_xapian_db_add(struct flatcurve_fts_backend *backend, struct flatcurve_xapian_db_path *dbpath, enum flatcurve_xapian_db_type type, bool open_wdb) { struct flatcurve_xapian_db_path *newpath; struct flatcurve_xapian_db *o, *xdb; struct flatcurve_xapian *x = backend->xapian; enum flatcurve_xapian_wdb wopts = FLATCURVE_XAPIAN_WDB_CREATE; if ((type != FLATCURVE_XAPIAN_DB_TYPE_INDEX) && (type != FLATCURVE_XAPIAN_DB_TYPE_CURRENT)) return NULL; xdb = p_new(x->pool, struct flatcurve_xapian_db, 1); xdb->dbpath = dbpath; xdb->type = type; if (open_wdb && (fts_flatcurve_xapian_write_db_get(backend, xdb, wopts) == NULL)) return NULL; hash_table_insert(x->dbs, dbpath->fname, xdb); /* If multiple current DBs exist, rename the oldest. */ if ((type == FLATCURVE_XAPIAN_DB_TYPE_CURRENT) && (x->dbw_current != NULL)) { o = (strcmp(dbpath->fname, x->dbw_current->dbpath->fname) > 0) ? x->dbw_current : xdb; newpath = fts_flatcurve_xapian_rename_db(backend, o->dbpath); fts_flatcurve_xapian_close_db(backend, o, FLATCURVE_XAPIAN_DB_CLOSE_WDB); hash_table_remove(x->dbs, o->dbpath->fname); hash_table_insert(x->dbs, newpath->fname, o); o->dbpath = newpath; o->type = FLATCURVE_XAPIAN_DB_TYPE_INDEX; } if (xdb->type == FLATCURVE_XAPIAN_DB_TYPE_CURRENT) x->dbw_current = xdb; return xdb; } static int fts_flatcurve_xapian_lock(struct flatcurve_fts_backend *backend) { struct file_create_settings set; struct flatcurve_xapian *x = backend->xapian; i_zero(&set); set.lock_timeout_secs = FLATCURVE_XAPIAN_LOCK_TIMEOUT_SECS; set.lock_settings.close_on_free = TRUE; set.lock_settings.unlink_on_free = TRUE; set.lock_settings.lock_method = backend->parsed_lock_method; if (x->lock_path == NULL) { if (str_len(backend->volatile_dir) > 0) { unsigned char db_path_hash[MD5_RESULTLEN]; md5_get_digest(str_c(backend->db_path), str_len(backend->db_path), db_path_hash); x->lock_path = p_strdup_printf( x->pool, "%s/" FLATCURVE_XAPIAN_LOCK_FNAME ".%s", str_c(backend->volatile_dir), binary_to_hex(db_path_hash, sizeof(db_path_hash))); set.mkdir_mode = 0700; } else { x->lock_path = p_strdup_printf( x->pool, "%s" FLATCURVE_XAPIAN_LOCK_FNAME, str_c(backend->db_path)); } } bool created; const char *error; int ret = file_create_locked(x->lock_path, &set, &x->lock, &created, &error); if (ret < 0) e_error(backend->event, "file_create_locked(%s) failed: %m", x->lock_path); return ret; } static void fts_flatcurve_xapian_unlock(struct flatcurve_fts_backend *backend) { file_lock_free(&backend->xapian->lock); } static bool fts_flatcurve_xapian_db_read_add(struct flatcurve_fts_backend *backend, struct flatcurve_xapian_db *xdb) { struct flatcurve_xapian *x = backend->xapian; if (x->db_read == NULL) return TRUE; try { xdb->db = new Xapian::Database(xdb->dbpath->path); } catch (Xapian::Error &e) { e_debug(backend->event, "Cannot open DB (RO; %s); %s", xdb->dbpath->fname, e.get_description().c_str()); return FALSE; } fts_flatcurve_xapian_check_db_version(backend, xdb); ++x->shards; x->db_read->add_database(*(xdb->db)); fts_flatcurve_xapian_optimize_mailbox(backend); return TRUE; } static bool fts_flatcurve_xapian_create_current(struct flatcurve_fts_backend *backend, enum flatcurve_xapian_db_close copts) { std::ostringstream s; struct flatcurve_xapian_db *xdb; /* The current shard has filename of the format PREFIX.timestamp. This * ensures that we will catch any current DB renaming done by another * process (reopen() on the DB will fail, causing the entire DB to be * closed/reopened). */ s << FLATCURVE_XAPIAN_DB_CURRENT_PREFIX << i_microseconds(); xdb = fts_flatcurve_xapian_db_add( backend, fts_flatcurve_xapian_create_db_path(backend, s.str().c_str()), FLATCURVE_XAPIAN_DB_TYPE_CURRENT, TRUE); if (xdb == NULL || !fts_flatcurve_xapian_db_read_add(backend, xdb)) return FALSE; if (copts) fts_flatcurve_xapian_close_db(backend, xdb, copts); return TRUE; } static bool fts_flatcurve_xapian_db_populate(struct flatcurve_fts_backend *backend, enum flatcurve_xapian_db_opts opts) { bool dbs_exist, lock, no_create, ret; struct flatcurve_xapian_db_iter *iter; struct flatcurve_xapian *x = backend->xapian; dbs_exist = (hash_table_count(backend->xapian->dbs) > 0); no_create = HAS_ALL_BITS(opts, FLATCURVE_XAPIAN_DB_NOCREATE_CURRENT); if (dbs_exist && (no_create || (x->dbw_current != NULL))) return TRUE; if (no_create) { struct stat st; if (stat(str_c(backend->db_path), &st) == 0) lock = S_ISDIR(st.st_mode); else if (errno == ENOENT) lock = FALSE; else { e_error(backend->event, "stat(%s) failed: %m", str_c(backend->db_path)); } } else { if (mailbox_list_mkdir_root(backend->backend.ns->list, str_c(backend->db_path), MAILBOX_LIST_PATH_TYPE_INDEX) < 0) { e_error(backend->event, "Cannot create DB (RW); %s", str_c(backend->db_path)); return FALSE; } lock = TRUE; } if (lock && (fts_flatcurve_xapian_lock(backend) < 0)) return FALSE; if (!dbs_exist) { if ((iter = fts_flatcurve_xapian_db_iter_init(backend, opts)) == NULL) { fts_flatcurve_xapian_unlock(backend); return FALSE; } while (fts_flatcurve_xapian_db_iter_next(iter)) { (void)fts_flatcurve_xapian_db_add(backend, iter->path, iter->type, FALSE); } fts_flatcurve_xapian_db_iter_deinit(&iter); } ret = (!no_create && (x->dbw_current == NULL)) ? fts_flatcurve_xapian_create_current(backend, (enum flatcurve_xapian_db_close)(HAS_ALL_BITS(opts, FLATCURVE_XAPIAN_DB_NOCLOSE_CURRENT) ? 0 : FLATCURVE_XAPIAN_DB_CLOSE_WDB)) : TRUE; fts_flatcurve_xapian_unlock(backend); return ret; } static struct flatcurve_xapian_db * fts_flatcurve_xapian_write_db_current(struct flatcurve_fts_backend *backend, enum flatcurve_xapian_db_opts opts) { enum flatcurve_xapian_wdb wopts = ENUM_EMPTY(flatcurve_xapian_wdb); struct flatcurve_xapian *x = backend->xapian; if ((x->dbw_current != NULL) && (x->dbw_current->dbw != NULL)) return x->dbw_current; opts = (enum flatcurve_xapian_db_opts) (opts | FLATCURVE_XAPIAN_DB_NOCLOSE_CURRENT); /* dbw_current can be NULL if FLATCURVE_XAPIAN_DB_NOCREATE_CURRENT * is set in opts. */ if (!fts_flatcurve_xapian_db_populate(backend, opts) || (x->dbw_current == NULL)) return NULL; return fts_flatcurve_xapian_write_db_get(backend, x->dbw_current, wopts); } static Xapian::Database * fts_flatcurve_xapian_read_db(struct flatcurve_fts_backend *backend, enum flatcurve_xapian_db_opts opts) { struct hash_iterate_context *iter; void *key, *val; struct fts_flatcurve_xapian_db_stats stats; struct flatcurve_xapian *x = backend->xapian; struct flatcurve_xapian_db *xdb; if (x->db_read != NULL) { try { (void)x->db_read->reopen(); } catch (Xapian::DatabaseNotFoundError &e) { /* This means that the underlying databases have * changed (i.e. DB rotation by another process). * Close all DBs and reopen. */ fts_flatcurve_xapian_close(backend); return fts_flatcurve_xapian_read_db(backend, opts); } return x->db_read; } if (!fts_flatcurve_xapian_db_populate(backend, opts)) return NULL; if (HAS_ALL_BITS(opts, FLATCURVE_XAPIAN_DB_IGNORE_EMPTY) && (hash_table_count(x->dbs) == 0)) return NULL; x->db_read = new Xapian::Database(); iter = hash_table_iterate_init(x->dbs); while (hash_table_iterate(iter, x->dbs, &key, &val)) { xdb = (struct flatcurve_xapian_db *)val; if (!fts_flatcurve_xapian_db_read_add(backend, xdb)) { /* If we can't open a DB, delete it. */ fts_flatcurve_xapian_delete(backend, xdb->dbpath); hash_table_remove(x->dbs, key); } } hash_table_iterate_deinit(&iter); fts_flatcurve_xapian_mailbox_stats(backend, &stats); e_debug(backend->event, "Opened DB (RO) messages=%u version=%u " "shards=%u", stats.messages, stats.version, stats.shards); return x->db_read; } void fts_flatcurve_xapian_mailbox_check(struct flatcurve_fts_backend *backend, struct fts_flatcurve_xapian_db_check *check) { struct hash_iterate_context *iter; void *key, *val; enum flatcurve_xapian_db_opts opts = (enum flatcurve_xapian_db_opts) (FLATCURVE_XAPIAN_DB_NOCREATE_CURRENT | FLATCURVE_XAPIAN_DB_IGNORE_EMPTY); struct flatcurve_xapian *x = backend->xapian; struct flatcurve_xapian_db *xdb; i_zero(check); if (fts_flatcurve_xapian_read_db(backend, opts) == NULL) return; iter = hash_table_iterate_init(x->dbs); while (hash_table_iterate(iter, x->dbs, &key, &val)) { xdb = (struct flatcurve_xapian_db *)val; try { check->errors += Xapian::Database::check( std::string(xdb->dbpath->path), Xapian::DBCHECK_FIX, NULL); } catch (const Xapian::Error &e) { e_debug(backend->event, "Check failed; %s", e.get_description().c_str()); } ++check->shards; } hash_table_iterate_deinit(&iter); } bool fts_flatcurve_xapian_mailbox_rotate(struct flatcurve_fts_backend *backend) { enum flatcurve_xapian_db_opts opts = (enum flatcurve_xapian_db_opts) (FLATCURVE_XAPIAN_DB_NOCREATE_CURRENT | FLATCURVE_XAPIAN_DB_IGNORE_EMPTY); struct flatcurve_xapian_db *xdb; if ((xdb = fts_flatcurve_xapian_write_db_current(backend, opts)) == NULL) return FALSE; fts_flatcurve_xapian_close_db(backend, xdb, FLATCURVE_XAPIAN_DB_CLOSE_ROTATE); return TRUE; } void fts_flatcurve_xapian_mailbox_stats(struct flatcurve_fts_backend *backend, struct fts_flatcurve_xapian_db_stats *stats) { enum flatcurve_xapian_db_opts opts = (enum flatcurve_xapian_db_opts) (FLATCURVE_XAPIAN_DB_NOCREATE_CURRENT | FLATCURVE_XAPIAN_DB_IGNORE_EMPTY); struct flatcurve_xapian *x = backend->xapian; if ((x->db_read == NULL) && (fts_flatcurve_xapian_read_db(backend, opts) == NULL)) { i_zero(stats); } else { stats->messages = x->db_read->get_doccount(); stats->shards = x->shards; stats->version = FLATCURVE_XAPIAN_DB_VERSION; } } static void fts_flatcurve_xapian_mailbox_terms_do(struct flatcurve_fts_backend *backend, HASH_TABLE_TYPE(term_counter) terms, const char *prefix) { unsigned int counter; Xapian::Database *db; const char *key, *pkey; void *k, *v; enum flatcurve_xapian_db_opts opts = (enum flatcurve_xapian_db_opts) (FLATCURVE_XAPIAN_DB_NOCREATE_CURRENT | FLATCURVE_XAPIAN_DB_IGNORE_EMPTY); Xapian::TermIterator t, tend; if ((db = fts_flatcurve_xapian_read_db(backend, opts)) == NULL) return; for (t = db->allterms_begin(prefix), tend = db->allterms_end(prefix); t != tend; ++t) { const std::string &term = *t; key = term.data(); if (strlen(prefix) > 0) { if (strncmp(key, FLATCURVE_XAPIAN_BOOLEAN_FIELD_PREFIX, 1) != 0) continue; ++key; } else if (strncmp(key, FLATCURVE_XAPIAN_ALL_HEADERS_PREFIX, 1) == 0) { ++key; } else if ((strncmp(key, FLATCURVE_XAPIAN_BOOLEAN_FIELD_PREFIX, 1) == 0) || (strncmp(key, FLATCURVE_XAPIAN_HEADER_PREFIX, 1) == 0)) { continue; } if (hash_table_lookup_full(terms, key, &k, &v)) { counter = POINTER_CAST_TO(v, unsigned int); pkey = (const char *)k; } else { counter = 0; /* Using backend memory pool, since expectation is * that this will only be called from doveadm. */ pkey = p_strdup(backend->pool, key); } counter += t.get_termfreq(); hash_table_update(terms, pkey, POINTER_CAST(counter)); } } void fts_flatcurve_xapian_mailbox_terms(struct flatcurve_fts_backend *backend, HASH_TABLE_TYPE(term_counter) terms) { fts_flatcurve_xapian_mailbox_terms_do(backend, terms, ""); } void fts_flatcurve_xapian_mailbox_headers(struct flatcurve_fts_backend *backend, HASH_TABLE_TYPE(term_counter) hdrs) { fts_flatcurve_xapian_mailbox_terms_do( backend, hdrs, FLATCURVE_XAPIAN_BOOLEAN_FIELD_PREFIX); } void fts_flatcurve_xapian_set_mailbox(struct flatcurve_fts_backend *backend) { event_set_append_log_prefix(backend->event, p_strdup_printf( backend->xapian->pool, FTS_FLATCURVE_LABEL "(%s): ", str_c(backend->boxname))); } static void fts_flatcurve_xapian_check_db_version(struct flatcurve_fts_backend *backend, struct flatcurve_xapian_db *xdb) { Xapian::Database *db = (xdb->dbw == NULL) ? xdb->db : xdb->dbw; std::ostringstream ss; int v; std::string ver; enum flatcurve_xapian_wdb wopts = ENUM_EMPTY(flatcurve_xapian_wdb); ver = db->get_metadata(FLATCURVE_XAPIAN_DB_VERSION_KEY); v = ver.empty() ? 0 : std::atoi(ver.c_str()); if (v == FLATCURVE_XAPIAN_DB_VERSION) return; /* If we need to upgrade DB, and this is NOT the write DB, open the * write DB, do the changes there, and reopen the read DB. */ if (!xdb->dbw) { (void)fts_flatcurve_xapian_write_db_get(backend, xdb, wopts); fts_flatcurve_xapian_close_db(backend, xdb, FLATCURVE_XAPIAN_DB_CLOSE_WDB); (void)xdb->db->reopen(); return; } /* 0->1: Added DB version. Always implicity update version when we * upgrade (done at end of this function). */ if (v == 0) ++v; ss << v; xdb->dbw->set_metadata(FLATCURVE_XAPIAN_DB_VERSION_KEY, ss.str()); /* Commit the changes now. */ xdb->dbw->commit(); } // Function requires read DB to have been opened static struct flatcurve_xapian_db * fts_flatcurve_xapian_uid_exists_db(struct flatcurve_fts_backend *backend, uint32_t uid) { struct hash_iterate_context *iter; void *key, *val; struct flatcurve_xapian_db *ret = NULL, *xdb; iter = hash_table_iterate_init(backend->xapian->dbs); while ((ret == NULL) && hash_table_iterate(iter, backend->xapian->dbs, &key, &val)) { xdb = (struct flatcurve_xapian_db *)val; try { (void)xdb->db->get_document(uid); ret = xdb; } catch (Xapian::DocNotFoundError &e) {} } hash_table_iterate_deinit(&iter); return ret; } static struct flatcurve_xapian_db * fts_flatcurve_xapian_write_db_by_uid(struct flatcurve_fts_backend *backend, uint32_t uid) { enum flatcurve_xapian_db_opts opts = ENUM_EMPTY(flatcurve_xapian_db_opts); enum flatcurve_xapian_wdb wopts = ENUM_EMPTY(flatcurve_xapian_wdb); struct flatcurve_xapian_db *xdb; (void)fts_flatcurve_xapian_read_db(backend, opts); xdb = fts_flatcurve_xapian_uid_exists_db(backend, uid); return (xdb == NULL) ? NULL : fts_flatcurve_xapian_write_db_get(backend, xdb, wopts); } static void fts_flatcurve_xapian_check_commit_limit(struct flatcurve_fts_backend *backend, struct flatcurve_xapian_db *xdb) { struct fts_flatcurve_user *fuser = backend->fuser; struct flatcurve_xapian *x = backend->xapian; ++x->doc_updates; ++xdb->changes; if ((xdb->type == FLATCURVE_XAPIAN_DB_TYPE_CURRENT) && (fuser->set.rotate_size > 0) && (xdb->dbw->get_doccount() >= fuser->set.rotate_size)) { fts_flatcurve_xapian_close_db( backend, xdb, FLATCURVE_XAPIAN_DB_CLOSE_ROTATE); } else if ((fuser->set.commit_limit > 0) && (x->doc_updates >= fuser->set.commit_limit)) { fts_flatcurve_xapian_close_dbs( backend, FLATCURVE_XAPIAN_DB_CLOSE_WDB_COMMIT); e_debug(backend->event, "Committing DB as update " "limit was reached; limit=%d", fuser->set.commit_limit); } } static void fts_flatcurve_xapian_clear_document(struct flatcurve_fts_backend *backend) { struct flatcurve_xapian *x = backend->xapian; enum flatcurve_xapian_db_opts opts = ENUM_EMPTY(flatcurve_xapian_db_opts); struct flatcurve_xapian_db *xdb; if ((x->doc == NULL) || ((xdb = fts_flatcurve_xapian_write_db_current(backend, opts)) == NULL)) return; try { xdb->dbw->replace_document(x->doc_uid, *x->doc); } catch (std::bad_alloc &b) { i_fatal(FTS_FLATCURVE_DEBUG_PREFIX "Out of memory " "when indexing mail (%s); UID=%d " "(Hint: increase indexing process vsz_limit or define " "smaller commit_limit value in plugin config)", b.what(), x->doc_uid); } catch (Xapian::Error &e) { e_warning(backend->event, "Could not write message data: " "uid=%u; %s", x->doc_uid, e.get_description().c_str()); } if (x->doc_created) delete(x->doc); x->doc = NULL; x->doc_created = FALSE; x->doc_uid = 0; fts_flatcurve_xapian_check_commit_limit(backend, xdb); } static void fts_flatcurve_xapian_close_db(struct flatcurve_fts_backend *backend, struct flatcurve_xapian_db *xdb, enum flatcurve_xapian_db_close opts) { bool commit = FALSE, rotate = FALSE; unsigned int diff; const char *fname; struct timeval now, start; struct flatcurve_xapian *x = backend->xapian; fts_flatcurve_xapian_clear_document(backend); if (xdb->dbw != NULL) { i_gettimeofday(&start); if (HAS_ANY_BITS(opts, FLATCURVE_XAPIAN_DB_CLOSE_WDB | FLATCURVE_XAPIAN_DB_CLOSE_MBOX)) { xdb->dbw->close(); delete(xdb->dbw); xdb->dbw = NULL; commit = TRUE; } else if (HAS_ANY_BITS(opts, FLATCURVE_XAPIAN_DB_CLOSE_WDB_COMMIT | FLATCURVE_XAPIAN_DB_CLOSE_ROTATE)) { xdb->dbw->commit(); commit = TRUE; } } if (commit) { x->doc_updates = 0; i_gettimeofday(&now); diff = (unsigned int) timeval_diff_msecs(&now, &start); if (xdb->changes > 0) e_debug(backend->event, "Committed %u changes to DB " "(RW; %s) in %u.%03u secs", xdb->changes, xdb->dbpath->fname, diff/1000, diff%1000); xdb->changes = 0; if ((xdb->type == FLATCURVE_XAPIAN_DB_TYPE_CURRENT) && (HAS_ALL_BITS(opts, FLATCURVE_XAPIAN_DB_CLOSE_ROTATE) || (backend->fuser->set.rotate_time > 0) && (diff > backend->fuser->set.rotate_time))) rotate = TRUE; } if (rotate && (fts_flatcurve_xapian_lock(backend) >= 0)) { fname = p_strdup(x->pool, xdb->dbpath->fname); if (!fts_flatcurve_xapian_create_current(backend, (enum flatcurve_xapian_db_close)(x->closing ? FLATCURVE_XAPIAN_DB_CLOSE_MBOX : 0))) e_debug(backend->event, "Error when rotating DB (%s)", xdb->dbpath->fname); else e_debug(event_create_passthrough(backend->event)-> set_name("fts_flatcurve_rotate")-> add_str("mailbox", str_c(backend->boxname))-> event(), "Rotating index (from: %s, to: %s)", fname, xdb->dbpath->fname); fts_flatcurve_xapian_unlock(backend); } if ((xdb->db != NULL) && HAS_ANY_BITS(opts, FLATCURVE_XAPIAN_DB_CLOSE_DB | FLATCURVE_XAPIAN_DB_CLOSE_MBOX)) { delete(xdb->db); xdb->db = NULL; } } static void fts_flatcurve_xapian_close_dbs(struct flatcurve_fts_backend *backend, enum flatcurve_xapian_db_close opts) { struct hash_iterate_context *iter; void *key, *val; struct flatcurve_xapian *x = backend->xapian; iter = hash_table_iterate_init(x->dbs); while (hash_table_iterate(iter, x->dbs, &key, &val)) { fts_flatcurve_xapian_close_db( backend, (struct flatcurve_xapian_db *)val, opts); } hash_table_iterate_deinit(&iter); } void fts_flatcurve_xapian_refresh(struct flatcurve_fts_backend *backend) { fts_flatcurve_xapian_close_dbs(backend, FLATCURVE_XAPIAN_DB_CLOSE_WDB); } void fts_flatcurve_xapian_close(struct flatcurve_fts_backend *backend) { struct flatcurve_xapian *x = backend->xapian; x->closing = TRUE; fts_flatcurve_xapian_close_dbs(backend, FLATCURVE_XAPIAN_DB_CLOSE_MBOX); x->closing = FALSE; hash_table_clear(x->dbs, TRUE); x->lock_path = NULL; x->dbw_current = NULL; x->shards = 0; if (x->db_read != NULL) { x->db_read->close(); delete(x->db_read); x->db_read = NULL; } p_clear(x->pool); } static uint32_t fts_flatcurve_xapian_get_last_uid_query(struct flatcurve_fts_backend *backend ATTR_UNUSED, Xapian::Database *db) { Xapian::Enquire enquire(*db); Xapian::MSet m; enquire.set_docid_order(Xapian::Enquire::DESCENDING); enquire.set_query(Xapian::Query::MatchAll); m = enquire.get_mset(0, 1); return (m.empty()) ? 0 : m.begin().get_document().get_docid(); } void fts_flatcurve_xapian_get_last_uid(struct flatcurve_fts_backend *backend, uint32_t *last_uid_r) { Xapian::Database *db; enum flatcurve_xapian_db_opts opts = (enum flatcurve_xapian_db_opts) (FLATCURVE_XAPIAN_DB_NOCREATE_CURRENT | FLATCURVE_XAPIAN_DB_IGNORE_EMPTY); if ((db = fts_flatcurve_xapian_read_db(backend, opts)) != NULL) { try { /* Optimization: if last used ID still exists in * mailbox, this is a cheap call. */ *last_uid_r = db->get_document(db->get_lastdocid()) .get_docid(); return; } catch (Xapian::DocNotFoundError &e) { /* Last used Xapian ID is no longer in the DB. Need * to do a manual search for the last existing ID. */ *last_uid_r = fts_flatcurve_xapian_get_last_uid_query(backend, db); return; } catch (Xapian::InvalidArgumentError &e) { // Document ID is 0 } } *last_uid_r = 0; } int fts_flatcurve_xapian_uid_exists(struct flatcurve_fts_backend *backend, uint32_t uid) { enum flatcurve_xapian_db_opts opts = (enum flatcurve_xapian_db_opts) (FLATCURVE_XAPIAN_DB_NOCREATE_CURRENT | FLATCURVE_XAPIAN_DB_IGNORE_EMPTY); return (fts_flatcurve_xapian_read_db(backend, opts) == NULL) ? -1 : (int)(fts_flatcurve_xapian_uid_exists_db(backend, uid) != NULL); } void fts_flatcurve_xapian_expunge(struct flatcurve_fts_backend *backend, uint32_t uid) { struct flatcurve_xapian_db *xdb; xdb = fts_flatcurve_xapian_write_db_by_uid(backend, uid); if (xdb == NULL) { e_debug(backend->event, "Expunge failed uid=%u; UID not found", uid); return; } try { xdb->dbw->delete_document(uid); fts_flatcurve_xapian_check_commit_limit(backend, xdb); } catch (Xapian::Error &e) { e_debug(backend->event, "update_expunge (%s)", e.get_description().c_str()); } } bool fts_flatcurve_xapian_init_msg(struct flatcurve_fts_backend_update_context *ctx) { enum flatcurve_xapian_db_opts opts = ENUM_EMPTY(flatcurve_xapian_db_opts); struct flatcurve_xapian *x = ctx->backend->xapian; struct flatcurve_xapian_db *xdb; if (ctx->uid == x->doc_uid) { return TRUE; } fts_flatcurve_xapian_clear_document(ctx->backend); if ((xdb = fts_flatcurve_xapian_write_db_current(ctx->backend, opts)) == NULL) return FALSE; try { (void)xdb->dbw->get_document(ctx->uid); return FALSE; } catch (Xapian::DocNotFoundError &e) { x->doc = new Xapian::Document(); x->doc_created = TRUE; } catch (Xapian::Error &e) { ctx->ctx.failed = TRUE; return FALSE; } x->doc_uid = ctx->uid; return TRUE; } void fts_flatcurve_xapian_index_header(struct flatcurve_fts_backend_update_context *ctx, const unsigned char *data, size_t size) { struct fts_flatcurve_user *fuser = ctx->backend->fuser; std::string h; const char *p = (const char *)data; struct flatcurve_xapian *x = ctx->backend->xapian; if (!fts_flatcurve_xapian_init_msg(ctx)) return; if (str_len(ctx->hdr_name)) { h = str_lcase(str_c_modifiable(ctx->hdr_name)); x->doc->add_boolean_term( FLATCURVE_XAPIAN_BOOLEAN_FIELD_PREFIX + h); } if (ctx->indexed_hdr) h = str_ucase(str_c_modifiable(ctx->hdr_name)); do { std::string t (p, size); /* Capital ASCII letters at the beginning of a Xapian term are * treated as a "term prefix". Check for a leading ASCII * capital, and lowercase if necessary, to ensure the term * is not confused with a "term prefix". */ if (i_isupper(t[0])) t[0] = i_tolower(t[0]); if (ctx->indexed_hdr) { x->doc->add_term( FLATCURVE_XAPIAN_HEADER_PREFIX + h + t); } x->doc->add_term(FLATCURVE_XAPIAN_ALL_HEADERS_PREFIX + t); unsigned int csize = uni_utf8_char_bytes(*p); p += csize; size -= csize; } while (fuser->set.substring_search && (size >= 0) && (uni_utf8_strlen_n(p, size) >= fuser->set.min_term_size)); } void fts_flatcurve_xapian_index_body(struct flatcurve_fts_backend_update_context *ctx, const unsigned char *data, size_t size) { struct fts_flatcurve_user *fuser = ctx->backend->fuser; const char *p = (const char *)data; struct flatcurve_xapian *x = ctx->backend->xapian; if (!fts_flatcurve_xapian_init_msg(ctx)) return; do { std::string t (p, size); /* Capital ASCII letters at the beginning of a Xapian term are * treated as a "term prefix". Check for a leading ASCII * capital, and lowercase if necessary, to ensure the term * is not confused with a "term prefix". */ if (i_isupper(t[0])) t[0] = i_tolower(t[0]); x->doc->add_term(t); unsigned int csize = uni_utf8_char_bytes(*p); p += csize; size -= csize; } while (fuser->set.substring_search && (size >= 0) && (uni_utf8_strlen_n(p, size) >= fuser->set.min_term_size)); } void fts_flatcurve_xapian_delete_index(struct flatcurve_fts_backend *backend) { fts_flatcurve_xapian_close(backend); fts_flatcurve_xapian_delete(backend, NULL); } #ifdef XAPIAN_HAS_COMPACT static bool fts_flatcurve_xapian_optimize_rebuild(struct flatcurve_fts_backend *backend, Xapian::Database *db, struct flatcurve_xapian_db_path *path) { Xapian::Document doc; Xapian::Enquire enquire(*db); Xapian::MSetIterator i; Xapian::MSet m; unsigned int updates = 0; struct flatcurve_xapian *x = backend->xapian; struct flatcurve_xapian_db *xdb; /* Create the optimize shard. */ xdb = p_new(x->pool, struct flatcurve_xapian_db, 1); xdb->dbpath = path; xdb->type = FLATCURVE_XAPIAN_DB_TYPE_OPTIMIZE; if (fts_flatcurve_xapian_write_db_get(backend, xdb, FLATCURVE_XAPIAN_WDB_CREATE) == NULL) return FALSE; enquire.set_docid_order(Xapian::Enquire::ASCENDING); enquire.set_query(Xapian::Query::MatchAll); m = enquire.get_mset(0, db->get_doccount()); i = m.begin(); while (i != m.end()) { doc = i.get_document(); try { xdb->dbw->replace_document(doc.get_docid(), doc); } catch (Xapian::Error &e) { return FALSE; } if (++updates > FLATCURVE_MANUAL_OPTIMIZE_COMMIT_LIMIT) { xdb->dbw->commit(); updates = 0; } ++i; } fts_flatcurve_xapian_close_db(backend, xdb, FLATCURVE_XAPIAN_DB_CLOSE_WDB); return TRUE; } // Return value = whether to output debug error message; not success static bool fts_flatcurve_xapian_optimize_box_do(struct flatcurve_fts_backend *backend, Xapian::Database *db) { unsigned int diff; struct hash_iterate_context *hiter; struct flatcurve_xapian_db_iter *iter; void *key, *val; struct flatcurve_xapian_db_path *n, *o; struct timeval now, start; enum flatcurve_xapian_db_opts opts = ENUM_EMPTY(flatcurve_xapian_db_opts); struct flatcurve_xapian *x = backend->xapian; enum flatcurve_xapian_wdb wopts = ENUM_EMPTY(flatcurve_xapian_wdb); /* We need to lock all of the mailboxes so nothing changes while we * are optimizing. */ hiter = hash_table_iterate_init(x->dbs); while (hash_table_iterate(hiter, x->dbs, &key, &val)) { (void)fts_flatcurve_xapian_write_db_get( backend, (struct flatcurve_xapian_db *)val, wopts); } hash_table_iterate_deinit(&hiter); /* Create the optimize target. */ o = fts_flatcurve_xapian_create_db_path(backend, FLATCURVE_XAPIAN_DB_OPTIMIZE); fts_flatcurve_xapian_delete(backend, o); i_gettimeofday(&start); try { try { (void)db->reopen(); db->compact(o->path, Xapian::DBCOMPACT_NO_RENUMBER | Xapian::DBCOMPACT_MULTIPASS | Xapian::Compactor::FULLER); } catch (Xapian::InvalidOperationError &e) { /* This exception is not as specific as it could be... * but the likely reason it happens is due to * Xapian::DBCOMPACT_NO_RENUMBER and shards having * disjoint ranges of UIDs (e.g. shard 1 = 1..2, shard * 2 = 2..3). Xapian, as of 1.4.18, cannot handle this * situation. Since we will never be able to compact * this data unless we do something about it, the * options are either 1) delete the index totally and * start fresh (not great for large mailboxes), or to * incrementally build the optimized DB by walking * through all DBs and copying, ignoring duplicate * documents. Let's try to be awesome and do the * latter. */ e_debug(backend->event, "Native optimize failed, " "fallback to manual optimization; %s", e.get_description().c_str()); if (!fts_flatcurve_xapian_optimize_rebuild(backend, db, o)) throw; } } catch (Xapian::Error &e) { e_error(backend->event, "Optimize failed; %s", e.get_description().c_str()); return TRUE; } n = p_new(x->pool, struct flatcurve_xapian_db_path, 1); n->fname = p_strdup(x->pool, o->fname); n->path = p_strdup(x->pool, o->path); /* Delete old indexes. */ if ((iter = fts_flatcurve_xapian_db_iter_init(backend, opts)) == NULL) return FALSE; while (fts_flatcurve_xapian_db_iter_next(iter)) { if ((iter->type == FLATCURVE_XAPIAN_DB_TYPE_INDEX) || (iter->type == FLATCURVE_XAPIAN_DB_TYPE_CURRENT)) fts_flatcurve_xapian_delete(backend, iter->path); } fts_flatcurve_xapian_db_iter_deinit(&iter); /* Rename optimize index to an active index. */ if (fts_flatcurve_xapian_rename_db(backend, n) == NULL) { fts_flatcurve_xapian_delete(backend, o); return FALSE; } i_gettimeofday(&now); diff = (unsigned int) timeval_diff_msecs(&now, &start); e_debug(backend->event, "Optimized DB in %u.%03u secs", diff/1000, diff%1000); return TRUE; } #endif void fts_flatcurve_xapian_optimize_box(struct flatcurve_fts_backend *backend) { #ifdef XAPIAN_HAS_COMPACT Xapian::Database *db; enum flatcurve_xapian_db_opts opts = (enum flatcurve_xapian_db_opts) (FLATCURVE_XAPIAN_DB_NOCREATE_CURRENT | FLATCURVE_XAPIAN_DB_IGNORE_EMPTY); if ((db = fts_flatcurve_xapian_read_db(backend, opts)) == NULL) return; if (backend->xapian->deinit && !fts_flatcurve_xapian_need_optimize(backend)) { fts_flatcurve_xapian_close(backend); return; } e_debug(event_create_passthrough(backend->event)-> set_name("fts_flatcurve_optimize")-> add_str("mailbox", str_c(backend->boxname))->event(), "Optimizing"); if ((fts_flatcurve_xapian_lock(backend) >= 0) && (!fts_flatcurve_xapian_optimize_box_do(backend, db))) e_error(backend->event, "Optimize failed"); fts_flatcurve_xapian_close(backend); fts_flatcurve_xapian_unlock(backend); #endif } static void fts_flatcurve_build_query_arg_term(struct flatcurve_fts_query *query, struct mail_search_arg *arg, const char *term) { const char *hdr; bool maybe_or = FALSE; struct flatcurve_fts_query_xapian_maybe *mquery; Xapian::Query::op op = Xapian::Query::OP_INVALID; Xapian::Query *oldq, q; struct flatcurve_fts_query_xapian *x = query->xapian; if (x->start) { if (x->and_search) { op = Xapian::Query::OP_AND; str_append(query->qtext, " AND "); } else { op = Xapian::Query::OP_OR; str_append(query->qtext, " OR "); } } x->start = TRUE; if (arg->match_not) str_append(query->qtext, "NOT "); switch (arg->type) { case SEARCH_TEXT: q = Xapian::Query(Xapian::Query::OP_OR, Xapian::Query(Xapian::Query::OP_WILDCARD, t_strdup_printf("%s%s", FLATCURVE_XAPIAN_ALL_HEADERS_PREFIX, term)), Xapian::Query(Xapian::Query::OP_WILDCARD, term)); str_printfa(query->qtext, "(%s:%s* OR %s:%s*)", FLATCURVE_XAPIAN_ALL_HEADERS_QP, term, FLATCURVE_XAPIAN_BODY_QP, term); break; case SEARCH_BODY: q = Xapian::Query(Xapian::Query::OP_WILDCARD, term); str_printfa(query->qtext, "%s:%s*", FLATCURVE_XAPIAN_BODY_QP, term); break; case SEARCH_HEADER: case SEARCH_HEADER_ADDRESS: case SEARCH_HEADER_COMPRESS_LWSP: if (strlen(term)) { if (fts_header_want_indexed(arg->hdr_field_name)) { q = Xapian::Query( Xapian::Query::OP_WILDCARD, t_strdup_printf("%s%s%s", FLATCURVE_XAPIAN_HEADER_PREFIX, t_str_ucase(arg->hdr_field_name), term)); str_printfa(query->qtext, "%s%s:%s*", FLATCURVE_XAPIAN_HEADER_QP, t_str_lcase(arg->hdr_field_name), term); } else { q = Xapian::Query( Xapian::Query::OP_WILDCARD, t_strdup_printf("%s%s", FLATCURVE_XAPIAN_ALL_HEADERS_PREFIX, term)); str_printfa(query->qtext, "%s:%s*", FLATCURVE_XAPIAN_ALL_HEADERS_QP, term); /* Non-indexed headers only match if it * appears in the general pool of header * terms for the message, not to a specific * header, so this is only a maybe match. */ if (x->and_search) x->maybe = TRUE; else maybe_or = TRUE; } } else { hdr = t_str_lcase(arg->hdr_field_name); q = Xapian::Query(t_strdup_printf("%s%s", FLATCURVE_XAPIAN_BOOLEAN_FIELD_PREFIX, hdr)); str_printfa(query->qtext, "%s:%s", FLATCURVE_XAPIAN_HEADER_BOOL_QP, hdr); } break; } if (arg->match_not) q = Xapian::Query(Xapian::Query::OP_AND_NOT, Xapian::Query::MatchAll, q); if (maybe_or) { /* Maybe searches are not added to the "master search" query if this * is an OR search; they will be run independently. Matches will be * placed in the maybe results array. */ if (!array_is_created(&x->maybe_queries)) p_array_init(&x->maybe_queries, query->pool, 4); mquery = array_append_space(&x->maybe_queries); mquery->query = new Xapian::Query(std_move(q)); } else if (x->query == NULL) { x->query = new Xapian::Query(std_move(q)); } else { oldq = x->query; x->query = new Xapian::Query(op, *(x->query), q); delete(oldq); } } static void fts_flatcurve_build_query_arg(struct flatcurve_fts_query *query, struct mail_search_arg *arg) { const char *term; if (arg->no_fts) return; switch (arg->type) { case SEARCH_TEXT: case SEARCH_BODY: case SEARCH_HEADER: case SEARCH_HEADER_ADDRESS: case SEARCH_HEADER_COMPRESS_LWSP: /* Valid search term. Set match_always, as required by FTS * API, to avoid this argument being looked up later via * regular search code. */ arg->match_always = TRUE; break; case SEARCH_MAILBOX: /* doveadm will pass this through in 'doveadm search' * commands with a 'mailbox' search argument. The code has * already handled setting the proper mailbox by this point * so just ignore this. */ return; case SEARCH_OR: case SEARCH_SUB: /* FTS API says to ignore these. */ return; default: /* We should never get here - this is a search argument that * we don't understand how to handle that has leaked to this * point. For performance reasons, we will ignore this * argument and err on the side of returning too many * results (rather than falling back to slow, manual * search). */ return; } if (strlen(arg->value.str)) { /* Prepare search term. Phrase searching is not supported * natively (FTS core provides index terms without positional * context) so we can only do single term searching with * Xapian. Therefore, if we do see a multi-term search, ignore * (since, as of v2.3.19, FTS core will send both the * phrase search and individual search terms separately as * part of the same query. */ if (strchr(arg->value.str, ' ') != NULL) return; term = arg->value.str; } else { /* This is an existence search. */ term = ""; } fts_flatcurve_build_query_arg_term(query, arg, term); } void fts_flatcurve_xapian_build_query(struct flatcurve_fts_query *query) { struct mail_search_arg *args = query->args; struct flatcurve_fts_query_xapian *x; x = query->xapian = p_new(query->pool, struct flatcurve_fts_query_xapian, 1); if (query->match_all) { str_append(query->qtext, "[Match All]"); x->query = new Xapian::Query(Xapian::Query::MatchAll); return; } x->and_search = ((query->flags & FTS_LOOKUP_FLAG_AND_ARGS) != 0); for (; args != NULL ; args = args->next) { fts_flatcurve_build_query_arg(query, args); } } struct fts_flatcurve_xapian_query_iter * fts_flatcurve_xapian_query_iter_init(struct flatcurve_fts_query *query) { struct fts_flatcurve_xapian_query_iter *iter; iter = p_new(query->pool, struct fts_flatcurve_xapian_query_iter, 1); iter->init = FALSE; iter->main_query = TRUE; iter->query = query; iter->result = p_new(query->pool, struct fts_flatcurve_xapian_query_result, 1); return iter; } struct fts_flatcurve_xapian_query_result * fts_flatcurve_xapian_query_iter_next(struct fts_flatcurve_xapian_query_iter *iter) { Xapian::Query maybe, *q = NULL; const struct flatcurve_fts_query_xapian_maybe *mquery; enum flatcurve_xapian_db_opts opts = ENUM_EMPTY(flatcurve_xapian_db_opts); if (!iter->init) { iter->init = TRUE; /* Master query. */ if (iter->main_query) { if (iter->query->xapian->query == NULL) iter->main_query = FALSE; else q = iter->query->xapian->query; } /* Maybe queries. */ if (!iter->main_query && array_is_created(&iter->query->xapian->maybe_queries)) { maybe = Xapian::Query(); array_foreach(&iter->query->xapian->maybe_queries, mquery) maybe = Xapian::Query(Xapian::Query::OP_OR, maybe, *mquery->query); /* Add main query to merge Xapian scores correctly. */ if (iter->query->xapian->query != NULL) maybe = Xapian::Query(Xapian::Query::OP_AND_MAYBE, maybe, *iter->query->xapian->query); q = &maybe; } if ((q != NULL) && (iter->db == NULL)) iter->db = fts_flatcurve_xapian_read_db(iter->query->backend, opts); if ((q == NULL) || (iter->db == NULL)) return NULL; if (iter->enquire == NULL) { iter->enquire = new Xapian::Enquire(*iter->db); iter->enquire->set_docid_order(Xapian::Enquire::DONT_CARE); } iter->enquire->set_query(*q); try { iter->m = iter->enquire->get_mset(0, iter->db->get_doccount()); } catch (Xapian::DatabaseModifiedError &e) { /* Per documentation, this is only thrown if more than * one change has been made to the database. To * resolve you need to reopen the DB (Xapian can * handle a single snapshot of a modified DB natively, * so this only occurs if there have been multiple * writes). However, we ALWAYS want to use the * most up-to-date version, so we have already * explicitly called reopen() above. Thus, we should * never see this exception. */ i_unreached(); } iter->i = iter->m.begin(); } if (iter->i == iter->m.end()) { if (!iter->main_query) return NULL; iter->main_query = iter->init = FALSE; return fts_flatcurve_xapian_query_iter_next(iter); } iter->result->maybe = !iter->main_query; iter->result->score = iter->i.get_weight(); /* MSet docid can be an "interleaved" docid generated by * Xapian::Database when handling multiple DBs at once. Instead, we * want the "unique docid", which is obtained by looking at the * doc id from the Document object itself. */ iter->result->uid = iter->i.get_document().get_docid(); ++iter->i; return iter->result; } void fts_flatcurve_xapian_query_iter_deinit(struct fts_flatcurve_xapian_query_iter **_iter) { struct fts_flatcurve_xapian_query_iter *iter = *_iter; /* Need to explicitly call dtor, or else MSet doesn't release memory * allocated internally. */ *_iter = NULL; iter->i.~MSetIterator(); iter->m.~MSet(); delete(iter->enquire); p_free(iter->query->pool, iter->result); p_free(iter->query->pool, iter); } bool fts_flatcurve_xapian_run_query(struct flatcurve_fts_query *query, struct flatcurve_fts_result *r) { struct fts_flatcurve_xapian_query_iter *iter; struct fts_flatcurve_xapian_query_result *result; struct fts_score_map *score; if ((iter = fts_flatcurve_xapian_query_iter_init(query)) == NULL) return FALSE; while ((result = fts_flatcurve_xapian_query_iter_next(iter)) != NULL) { bool add_score = TRUE; if (result->maybe || query->xapian->maybe) { add_score = (!seq_range_exists(&r->uids, result->uid) && !seq_range_exists(&r->maybe_uids, result->uid)); seq_range_array_add(&r->maybe_uids, result->uid); } else seq_range_array_add(&r->uids, result->uid); if (add_score) { score = array_append_space(&r->scores); score->score = (float)result->score; score->uid = result->uid; } } fts_flatcurve_xapian_query_iter_deinit(&iter); return TRUE; } void fts_flatcurve_xapian_destroy_query(struct flatcurve_fts_query *query) { struct flatcurve_fts_query_xapian_maybe *mquery; delete(query->xapian->query); if (array_is_created(&query->xapian->maybe_queries)) { array_foreach_modifiable(&query->xapian->maybe_queries, mquery) { delete(mquery->query); } array_free(&query->xapian->maybe_queries); } } const char *fts_flatcurve_xapian_library_version() { return Xapian::version_string(); }
54,751
C++
.cpp
1,566
31.911239
175
0.704054
slusarz/dovecot-fts-flatcurve
39
8
1
LGPL-2.1
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,499
fts-backend-flatcurve-xapian.h
slusarz_dovecot-fts-flatcurve/src/fts-backend-flatcurve-xapian.h
/* Copyright (c) Michael Slusarz <slusarz@curecanti.org> * See the included COPYING file */ #ifndef FTS_BACKEND_FLATCURVE_XAPIAN_H #define FTS_BACKEND_FLATCURVE_XAPIAN_H struct fts_flatcurve_xapian_query_result { double score; uint32_t uid; bool maybe:1; }; struct fts_flatcurve_xapian_db_check { int errors; unsigned int shards; }; struct fts_flatcurve_xapian_db_stats { int messages; unsigned int shards; unsigned int version; }; HASH_TABLE_DEFINE_TYPE(term_counter, char *, void *); struct fts_flatcurve_xapian_query_iter; void fts_flatcurve_xapian_init(struct flatcurve_fts_backend *backend); void fts_flatcurve_xapian_refresh(struct flatcurve_fts_backend *backend); void fts_flatcurve_xapian_close(struct flatcurve_fts_backend *backend); void fts_flatcurve_xapian_deinit(struct flatcurve_fts_backend *backend); void fts_flatcurve_xapian_get_last_uid(struct flatcurve_fts_backend *backend, uint32_t *last_uid_r); /* Return -1 if DB doesn't exist, 0 if UID doesn't exist, 1 if UID exists */ int fts_flatcurve_xapian_uid_exists(struct flatcurve_fts_backend *backend, uint32_t uid); void fts_flatcurve_xapian_expunge(struct flatcurve_fts_backend *backend, uint32_t uid); bool fts_flatcurve_xapian_init_msg(struct flatcurve_fts_backend_update_context *ctx); void fts_flatcurve_xapian_index_header(struct flatcurve_fts_backend_update_context *ctx, const unsigned char *data, size_t size); void fts_flatcurve_xapian_index_body(struct flatcurve_fts_backend_update_context *ctx, const unsigned char *data, size_t size); void fts_flatcurve_xapian_optimize_box(struct flatcurve_fts_backend *backend); void fts_flatcurve_xapian_build_query(struct flatcurve_fts_query *query); bool fts_flatcurve_xapian_run_query(struct flatcurve_fts_query *query, struct flatcurve_fts_result *r); void fts_flatcurve_xapian_destroy_query(struct flatcurve_fts_query *query); void fts_flatcurve_xapian_delete_index(struct flatcurve_fts_backend *backend); struct fts_flatcurve_xapian_query_iter * fts_flatcurve_xapian_query_iter_init(struct flatcurve_fts_query *query); struct fts_flatcurve_xapian_query_result * fts_flatcurve_xapian_query_iter_next(struct fts_flatcurve_xapian_query_iter *iter); void fts_flatcurve_xapian_query_iter_deinit(struct fts_flatcurve_xapian_query_iter **_iter); void fts_flatcurve_xapian_mailbox_check(struct flatcurve_fts_backend *backend, struct fts_flatcurve_xapian_db_check *check); bool fts_flatcurve_xapian_mailbox_rotate(struct flatcurve_fts_backend *backend); void fts_flatcurve_xapian_mailbox_stats(struct flatcurve_fts_backend *backend, struct fts_flatcurve_xapian_db_stats *stats); void fts_flatcurve_xapian_mailbox_terms(struct flatcurve_fts_backend *backend, HASH_TABLE_TYPE(term_counter) terms); void fts_flatcurve_xapian_mailbox_headers(struct flatcurve_fts_backend *backend, HASH_TABLE_TYPE(term_counter) hdrs); void fts_flatcurve_xapian_set_mailbox(struct flatcurve_fts_backend *backend); const char *fts_flatcurve_xapian_library_version(); #endif
3,085
C++
.h
66
43.924242
87
0.787354
slusarz/dovecot-fts-flatcurve
39
8
1
LGPL-2.1
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,500
fts-backend-flatcurve.h
slusarz_dovecot-fts-flatcurve/src/fts-backend-flatcurve.h
/* Copyright (c) Michael Slusarz <slusarz@curecanti.org> * See the included COPYING file */ #ifndef FTS_FLATCURVE_BACKEND_H #define FTS_FLATCURVE_BACKEND_H #include "file-lock.h" #include "fts-flatcurve-plugin.h" #define FTS_FLATCURVE_LABEL "fts-flatcurve" #define FTS_FLATCURVE_DEBUG_PREFIX FTS_FLATCURVE_LABEL ": " struct flatcurve_fts_backend { struct fts_backend backend; string_t *boxname, *db_path, *volatile_dir; struct event *event; struct fts_flatcurve_user *fuser; struct flatcurve_xapian *xapian; enum file_lock_method parsed_lock_method; pool_t pool; bool debug_init:1; }; struct flatcurve_fts_backend_update_context { struct fts_backend_update_context ctx; struct flatcurve_fts_backend *backend; enum fts_backend_build_key_type type; string_t *hdr_name; uint32_t uid; struct timeval start; bool indexed_hdr:1; bool skip_uid:1; }; struct flatcurve_fts_query { struct mail_search_arg *args; enum fts_lookup_flags flags; string_t *qtext; struct flatcurve_fts_backend *backend; struct flatcurve_fts_query_xapian *xapian; pool_t pool; bool match_all:1; }; struct flatcurve_fts_result { ARRAY_TYPE(fts_score_map) scores; ARRAY_TYPE(seq_range) maybe_uids; ARRAY_TYPE(seq_range) uids; }; void fts_backend_flatcurve_set_mailbox(struct flatcurve_fts_backend *backend, struct mailbox *box); void fts_backend_flatcurve_close_mailbox(struct flatcurve_fts_backend *backend); // Returns -1 on error, 0 if FTS directory doesn't exist, 1 on success int fts_backend_flatcurve_delete_dir(struct flatcurve_fts_backend *backend, const char *path); #endif
1,643
C++
.h
50
29.94
77
0.76145
slusarz/dovecot-fts-flatcurve
39
8
1
LGPL-2.1
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,501
fts-flatcurve-plugin.h
slusarz_dovecot-fts-flatcurve/src/fts-flatcurve-plugin.h
/* Copyright (c) Michael Slusarz <slusarz@curecanti.org> * See the included COPYING file */ #ifndef FTS_FLATCURVE_PLUGIN_H #define FTS_FLATCURVE_PLUGIN_H #include "module-context.h" #include "mail-user.h" #include "lib.h" #include "fts-api-private.h" #define FTS_FLATCURVE_USER_CONTEXT(obj) \ MODULE_CONTEXT(obj, fts_flatcurve_user_module) #define FTS_FLATCURVE_USER_CONTEXT_REQUIRE(obj) \ MODULE_CONTEXT_REQUIRE(obj, fts_flatcurve_user_module) struct fts_flatcurve_settings { unsigned int commit_limit; unsigned int min_term_size; unsigned int optimize_limit; unsigned int rotate_size; unsigned int rotate_time; bool substring_search; }; struct fts_flatcurve_user { union mail_user_module_context module_ctx; struct flatcurve_fts_backend *backend; struct fts_flatcurve_settings set; }; extern struct fts_backend fts_backend_flatcurve; extern MODULE_CONTEXT_DEFINE(fts_flatcurve_user_module, &mail_user_module_register); void fts_flatcurve_plugin_init(struct module *module); void fts_flatcurve_plugin_deinit(void); #endif
1,044
C++
.h
30
33.1
84
0.800995
slusarz/dovecot-fts-flatcurve
39
8
1
LGPL-2.1
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,502
helpers.cpp
valinet_WinOverview/WinOverviewLibrary/helpers.cpp
#include "pch.h" #include <Windows.h> #include <dwmapi.h> #include <algorithm> #include <conio.h> #pragma comment(lib, "Dwmapi.lib") #include "constants.h" #include "structs.h" #include "helpers.h" #include "workspace.h" void GetMonitors( _In_ std::vector<MonitorInfo> *monitors ) { GetMonitorsParams monitorParams; monitorParams.monitors = monitors; monitorParams.offset = reinterpret_cast<SIZE*>(malloc(sizeof(SIZE))); EnumDisplayMonitors( NULL, NULL, EnumDisplayMonitorsCallback, reinterpret_cast<LPARAM>(&monitorParams) ); // get monitor wallpaper GetWallpaperWindows(monitors); } BOOL CALLBACK EnumDisplayMonitorsCallback( _In_ HMONITOR hMonitor, _In_ HDC hdcMonitor, _In_ LPRECT lprcMonitor, _Out_ LPARAM dwData ) { GetMonitorsParams* params = reinterpret_cast<GetMonitorsParams*>(dwData); // get monitor coordinates MONITORINFOEX monitorInfo; monitorInfo.cbSize = sizeof(MONITORINFOEX); GetMonitorInfo( hMonitor, &monitorInfo ); MonitorInfo info; info.rcWork = monitorInfo.rcWork; info.rcMonitor = monitorInfo.rcMonitor; info.hMonitor = hMonitor; info.hWallpaperWnd = NULL; info.hAnimMutex = CreateSemaphore( NULL, 1, 1, NULL ); info.hAnimThread = NULL; info.hSearchThumb = NULL; info.hSearchHWnd = NULL; if (monitorInfo.rcMonitor.left < params->offset->cx) { params->offset->cx = monitorInfo.rcMonitor.left; } if (monitorInfo.rcMonitor.top < params->offset->cy) { params->offset->cy = monitorInfo.rcMonitor.top; } info.wallpaperOffset = params->offset; params->monitors->push_back(info); return TRUE; } // taken from: https://devblogs.microsoft.com/oldnewthing/20071008-00/?p=24863 BOOL IsAltTabWindow( _In_ HWND hwnd ) { TITLEBARINFO ti; HWND hwndTry, hwndWalk = NULL; if (!IsWindowVisible(hwnd)) return FALSE; hwndTry = GetAncestor(hwnd, GA_ROOTOWNER); while (hwndTry != hwndWalk) { hwndWalk = hwndTry; hwndTry = GetLastActivePopup(hwndWalk); if (IsWindowVisible(hwndTry)) break; } if (hwndWalk != hwnd) return FALSE; // the following removes some task tray programs and "Program Manager" //ti.cbSize = sizeof(ti); //GetTitleBarInfo(hwnd, &ti); //if (ti.rgstate[0] & STATE_SYSTEM_INVISIBLE) // return FALSE; // Tool windows should not be displayed either, these do not appear in the // task bar. if (GetWindowLong(hwnd, GWL_EXSTYLE) & WS_EX_TOOLWINDOW) return FALSE; return TRUE; } BOOL CALLBACK EnumWindowsProc( _In_ HWND hwnd, _Out_ LPARAM lParam ) { EnumWindowProcParam* params = reinterpret_cast<EnumWindowProcParam*>(lParam); // exclude Modern Apps that are suspended // taken from: https://stackoverflow.com/questions/43927156/enumwindows-returns-closed-windows-store-applications BOOL isCloacked; DwmGetWindowAttribute(hwnd, DWMWA_CLOAKED, &isCloacked, sizeof BOOL); if (IsAltTabWindow(hwnd) && !isCloacked && !IsIconic(hwnd) && MonitorFromWindow(hwnd, MONITOR_DEFAULTTONULL) == params->monitor.hMonitor) { WindowInfo info; info.hwnd = hwnd; GetWindowRect(hwnd, &info.rect); if (info.rect.right - info.rect.left != 0 || info.rect.bottom - info.rect.top != 0) { // normalize coordinates info.rect.right -= (params->monitor.realArea.left); info.rect.bottom -= (params->monitor.realArea.top); info.rect.left -= (params->monitor.realArea.left); info.rect.top -= (params->monitor.realArea.top); params->windows->push_back(info); } } return TRUE; } void GetWindowsOnMonitor( _In_ MonitorInfo monitor, _Out_ std::vector<WindowInfo> *windows ) { EnumWindowProcParam params; params.windows = windows; params.monitor = monitor; EnumWindows(EnumWindowsProc, reinterpret_cast<LPARAM>(&params)); } // based on: https://stackoverflow.com/questions/56132584/draw-on-windows-10-wallpaper-in-c BOOL CALLBACK GetWallpaperHwnd( _In_ HWND hwnd, _Out_ LPARAM lParam ) { std::vector<MonitorInfo>* monitors = reinterpret_cast<std::vector<MonitorInfo>*>(lParam); SIZE_T monitorNo; HWND p = FindWindowEx(hwnd, NULL, L"SHELLDLL_DefView", NULL); if (p) { HWND t = FindWindowEx(NULL, hwnd, L"WorkerW", NULL); if (t) { RECT rect; GetWindowRect(hwnd, &rect); for (monitorNo = 0; monitorNo < monitors->size(); ++monitorNo) { monitors->at(monitorNo).hWallpaperWnd = t; } } } return TRUE; } void GetWallpaperWindows( _Inout_ std::vector<MonitorInfo>* monitors ) { HWND progman = FindWindow(L"Progman", NULL); SendMessageTimeout(progman, 0x052C, 0, 0, SMTO_NORMAL, 1000, nullptr); EnumWindows(GetWallpaperHwnd, reinterpret_cast<LPARAM>(monitors)); } void GetWindowSlots( _In_ std::vector<WindowInfo>* windows, _In_ RECT area, _Out_ std::vector<Slot>* slots ) { Layout lastLayout; lastLayout.scale = -1; lastLayout.numRows = 0; lastLayout.numColumns = 0; for (int numRows = 1; ; numRows++) { int numColumns = ceil(windows->size() / numRows); if (numColumns == lastLayout.numColumns) break; Layout layout; layout.numRows = numRows; layout.numColumns = numColumns; computeLayout(windows, &layout, area); computeScaleAndSpace(&layout, area); if (!isBetterLayout(&lastLayout, &layout)) break; lastLayout = layout; } // compute slot where each live preview has to arrive computeWindowSlots(&lastLayout, area, slots); } HTHUMBNAIL RegisterLiveThumbnail( _In_ HWND dest, _In_ HWND src, _In_ RECT rect ) { HTHUMBNAIL thumb; int ret = DwmRegisterThumbnail(dest, src, &thumb); if (!ret) { DWM_THUMBNAIL_PROPERTIES props; props.dwFlags = DWM_TNP_VISIBLE | DWM_TNP_RECTDESTINATION | DWM_TNP_OPACITY; props.opacity = 255; props.fVisible = true; props.rcDestination = rect; props.fSourceClientAreaOnly = FALSE; ret = DwmUpdateThumbnailProperties(thumb, &props); } return thumb; } DWORD WINAPI animate( _Inout_ LPVOID lpParam ) { MonitorInfo* monitorInfo = reinterpret_cast<MonitorInfo*>(lpParam); AnimationInfo* threadArgs = &monitorInfo->animation; std::vector<Animation>& anim = threadArgs->animations; register int noValues; register int size = anim.size(); register int j = 0, k = 0; std::vector<RECT> rects; std::vector<double> opacities; switch (threadArgs->type) { case ANIMTYPE_PREVIEW: noValues = ANIMATION_DURATION_MS / threadArgs->delay_ms; rects.reserve(noValues * size); break; case ANIMTYPE_PREVIEW_FADE: noValues = FADE_DURATION_MS / threadArgs->delay_ms; opacities.reserve(noValues * size); break; case ANIMTYPE_MAIN_FADE: noValues = ANIMATION_DURATION_MS / threadArgs->delay_ms; opacities.reserve(noValues); } while (j <= noValues) { register int i; switch (threadArgs->type) { case ANIMTYPE_PREVIEW: { for (i = 0; i < size; ++i) { Animation& info = anim.at(i); POINT start = threadArgs->isOpening ? info.start : info.end; POINT end = threadArgs->isOpening ? info.end : info.start; double scale_start = threadArgs->isOpening ? 1.0 : info.scale; double scale_end = threadArgs->isOpening ? info.scale : 1.0; double x = linear(easeOutQuad((threadArgs->delay_ms * j) / ANIMATION_DURATION_MS * 1.0), start.x, end.x, ANIMATION_DURATION_MS); double y = linear(easeOutQuad((threadArgs->delay_ms * j) / ANIMATION_DURATION_MS * 1.0), start.y, end.y, ANIMATION_DURATION_MS); double s = linear(easeOutQuad((threadArgs->delay_ms * j) / ANIMATION_DURATION_MS * 1.0), scale_start, scale_end, ANIMATION_DURATION_MS); double w = info.w * s; double h = info.h * s; RECT rect; rect.left = x - w / 2; rect.top = y - h / 2; rect.bottom = h + rect.top; rect.right = w + rect.left; rects.push_back(rect); } break; } case ANIMTYPE_PREVIEW_FADE: { for (i = 0; i < size; ++i) { int start = threadArgs->isOpening ? 0 : 255; int end = threadArgs->isOpening ? 255 : 0; double opacity = linear(easeOutQuad((threadArgs->delay_ms * j) / FADE_DURATION_MS * 1.0), start, end, FADE_DURATION_MS); opacities.push_back(opacity); } break; } case ANIMTYPE_MAIN_FADE: { int start = threadArgs->isOpening ? 0 : 100; int end = threadArgs->isOpening ? 100 : 0; double opacity = (255.0 * linear(easeOutQuad((threadArgs->delay_ms * j) / ANIMATION_DURATION_MS * 1.0), start, end, ANIMATION_DURATION_MS)) / 100.0; opacities.push_back(opacity); break; } } j++; } HANDLE timer; /* Timer handle */ LARGE_INTEGER li; /* Time defintion */ /* Create timer */ if (!(timer = CreateWaitableTimer(NULL, TRUE, NULL))) return FALSE; j = 0; while (k <= noValues) { ULONGLONG startTime = GetTickCount64(); int i; switch (threadArgs->type) { case ANIMTYPE_PREVIEW: { for (i = 0; i < size; ++i) { DWM_THUMBNAIL_PROPERTIES props; props.dwFlags = DWM_TNP_RECTDESTINATION; props.rcDestination = rects.at(j + i); DwmUpdateThumbnailProperties(anim.at(i).thumb, &props); } break; } case ANIMTYPE_PREVIEW_FADE: { for (i = 0; i < size; ++i) { DWM_THUMBNAIL_PROPERTIES props; props.dwFlags = DWM_TNP_OPACITY; props.opacity = opacities.at(j + i); DwmUpdateThumbnailProperties(anim.at(i).thumb, &props); } break; } case ANIMTYPE_MAIN_FADE: { SetLayeredWindowAttributes(monitorInfo->hWnd, 0, opacities.at(k), LWA_ALPHA); } } k++; j += size; ULONGLONG elapsed = GetTickCount64() - startTime; double sleep = threadArgs->delay_ms - elapsed; //printf("%d ", GetTickCount64()); if (sleep > 0) { li.QuadPart = -sleep * 1000LL; //printf("%llu ", -li.QuadPart); if (!SetWaitableTimer(timer, &li, 0, NULL, NULL, FALSE)) { CloseHandle(timer); return FALSE; } /* Start & wait for timer */ WaitForSingleObject(timer, INFINITE); } } CloseHandle(timer); SendMessage(monitorInfo->hWnd, WM_THREAD_DONE, 0, 0); return 0; } BOOL BeginAnimateUpdate( _In_ MonitorInfo* info ) { DWORD dwWaitResult = WaitForSingleObject( info->hAnimMutex, 0); if (dwWaitResult == WAIT_OBJECT_0) { return TRUE; } return FALSE; } void EndAnimateUpdate( _In_ MonitorInfo* info ) { ReleaseSemaphore(info->hAnimMutex, 1, NULL); } BOOL DoAnimate( _In_ BOOL alreadyAcquired, _In_ UINT type, _In_ MonitorInfo* info, _In_ BOOL isOpening ) { BOOL bAcquired = TRUE; if (!alreadyAcquired) { bAcquired = BeginAnimateUpdate(info); } if (bAcquired) { info->animation.isOpening = isOpening; info->animation.type = type; info->hAnimThread = CreateThread( NULL, 0, animate, reinterpret_cast<LPVOID>(info), 0, NULL ); } return bAcquired; } bool SortHwndByZorder( _In_ HWND hWnd1, _In_ HWND hWnd2 ) { BOOL start = TRUE; HWND hwnd = NULL; while (TRUE) { if (start) hwnd = GetTopWindow(NULL); else hwnd = GetNextWindow(hwnd, GW_HWNDNEXT); if (hWnd1 == hwnd) { return false; } else if (hWnd2 == hwnd) { return true; } start = FALSE; } } bool SortAnimationsByHwndZorder( _In_ Animation a1, _In_ Animation a2 ) { return SortHwndByZorder(a1.hWnd, a2.hWnd); } RECT GetSearchRect( _In_ MonitorInfo* info ) { RECT rect; GetWindowRect(info->hSearchHWnd, &rect); RECT targetRect; targetRect.left = (info->area.right - info->area.left) / 2 - (rect.right - rect.left) / 2; targetRect.top = (info->area.bottom - info->area.top) / 2 - (rect.bottom - rect.top) / 2; targetRect.right = targetRect.left + rect.right - rect.left; targetRect.bottom = targetRect.top + rect.bottom - rect.top; return targetRect; } void ShowSearch( _In_ MonitorInfo* info, _In_ WPARAM wParam ) { if (DoAnimate(TRUE, ANIMTYPE_PREVIEW_FADE, info, FALSE)) { INPUT ip; ip.type = INPUT_KEYBOARD; ip.ki.wScan = 0; ip.ki.time = 0; ip.ki.dwExtraInfo = 0; ip.ki.wVk = VK_LWIN; ip.ki.dwFlags = 0; SendInput(1, &ip, sizeof(INPUT)); ip.ki.wVk = 0x51; ip.ki.dwFlags = 0; SendInput(1, &ip, sizeof(INPUT)); ip.ki.wVk = 0x51; ip.ki.dwFlags = KEYEVENTF_KEYUP; SendInput(1, &ip, sizeof(INPUT)); ip.ki.wVk = VK_LWIN; ip.ki.dwFlags = KEYEVENTF_KEYUP; SendInput(1, &ip, sizeof(INPUT)); TCHAR name[100]; HWND fWnd; do { fWnd = GetForegroundWindow(); GetClassName(fWnd, name, 100); } while (!wcsstr(name, TEXT("Windows.UI.Core.CoreW"))); Sleep(50); if (wParam != NULL) { BOOL wasShift = GetAsyncKeyState(VK_SHIFT); if (wasShift < 0) { ip.ki.wVk = VK_SHIFT; ip.ki.dwFlags = 0; SendInput(1, &ip, sizeof(INPUT)); } ip.ki.wVk = wParam; ip.ki.dwFlags = 0; SendInput(1, &ip, sizeof(INPUT)); ip.ki.wVk = wParam; ip.ki.dwFlags = KEYEVENTF_KEYUP; SendInput(1, &ip, sizeof(INPUT)); if (wasShift < 0) { ip.ki.wVk = VK_SHIFT; ip.ki.dwFlags = KEYEVENTF_KEYUP; SendInput(1, &ip, sizeof(INPUT)); } } info->hSearchHWnd = fWnd; RECT rect; GetWindowRect(fWnd, &rect); info->rcSearch = rect; SetWindowPos( fWnd, fWnd, info->area.left + (info->area.right - info->area.left) / 2 - (rect.right - rect.left) / 2, info->area.top + (info->area.bottom - info->area.top) / 2 - (rect.bottom - rect.top) / 2, 0, 0, SWP_NOZORDER | SWP_NOSIZE ); POINT pt; GetCursorPos(&pt); //if (pt.x >= rect.left && pt.x <= rect.right && pt.y >= rect.top && pt.y <= rect.bottom) //{ //LONG styles = GetWindowLong(info->hWnd, GWL_EXSTYLE); //SetWindowLong(info->hWnd, GWL_EXSTYLE, styles | WS_EX_TRANSPARENT); //SetWindowPos(info->hWnd, 0, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE); //} } }
16,404
C++
.cpp
500
23.914
161
0.569851
valinet/WinOverview
39
6
2
GPL-2.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,503
dllmain.cpp
valinet_WinOverview/WinOverviewLibrary/dllmain.cpp
// dllmain.cpp : Defines the entry point for the DLL application. #include "pch.h" #include <Windows.h> #include <windowsx.h> #include <objbase.h> #include <sddl.h> #include <tlhelp32.h> #include <vector> #include <algorithm> #include <assert.h> #pragma comment(lib, "gdi32.lib") #include "constants.h" #include "structs.h" #include "workspace.h" #include "helpers.h" HMODULE hpath = NULL; CreateWindowInBand pCreateWindowInBand = NULL; GetWindowBand pGetWindowBand = NULL; SetWindowBand pSetWindowBand = NULL; auto parentWindowClass = NULL; auto simpleWindowClass = NULL; auto bkgWindowClass = NULL; HWND previous = NULL; HWINEVENTHOOK fwndHook = NULL; HWND mainHwnd = NULL; HWND bkgHwnd = NULL; std::vector<MonitorInfo> monitors; void DetectSearchDismiss( HWINEVENTHOOK hWinEventHook, DWORD event, HWND hwnd, LONG idObject, LONG idChild, DWORD idEventThread, DWORD dwmsEventTime ) { TCHAR name[100]; GetClassName(hwnd, name, 100); if (!wcsstr(name, TEXT("HwndWrapper[DefaultDomain;;")) && !wcsstr(name, TEXT("Windows.UI.Core.CoreW")) && wcscmp(name, CLASS_NAME_BKG)) { UnhookWinEvent( fwndHook ); fwndHook = NULL; ShowWindow(mainHwnd, SW_SHOW); PostMessage(mainHwnd, WM_CLOSE, 1, 0); PostMessage(bkgHwnd, WM_CLOSE, 0, 0); mainHwnd = NULL; bkgHwnd = NULL; } } DWORD WINAPI CheckSearch( _Inout_ LPVOID lpParam ) { Sleep(400); MonitorInfo* monitorInfo = reinterpret_cast<MonitorInfo*>(lpParam); HWND fWnd = GetForegroundWindow(); if (monitorInfo->hWnd != fWnd && monitorInfo->hSearchHWnd != fWnd) { for (UINT z = 0; z < monitors.size(); ++z) { PostMessage(monitors.at(z).hWnd, WM_CLOSE, 2, 0); } } return 0; } LRESULT CALLBACK SimpleWindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { MonitorInfo* info; if (uMsg == WM_CREATE) { CREATESTRUCT* pCreate = reinterpret_cast<CREATESTRUCT*>(lParam); info = reinterpret_cast<MonitorInfo*>(pCreate->lpCreateParams); SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR)info); HINSTANCE hInstance = pCreate->hInstance; } else { LONG_PTR ptr = GetWindowLongPtr(hWnd, GWLP_USERDATA); info = reinterpret_cast<MonitorInfo*>(ptr); } switch (uMsg) { case WM_ACTIVATE: SetForegroundWindow(info->hWnd); break; } return DefWindowProc(hWnd, uMsg, wParam, lParam); } LRESULT CALLBACK WindowProcBkg(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { MonitorInfo* info; if (uMsg == WM_CREATE) { CREATESTRUCT* pCreate = reinterpret_cast<CREATESTRUCT*>(lParam); info = reinterpret_cast<MonitorInfo*>(pCreate->lpCreateParams); SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR)info); HINSTANCE hInstance = pCreate->hInstance; } else { LONG_PTR ptr = GetWindowLongPtr(hWnd, GWLP_USERDATA); info = reinterpret_cast<MonitorInfo*>(ptr); } switch (uMsg) { case WM_ACTIVATE: { if (info->hSearchHWnd && wParam == WA_ACTIVE) { BOOL bRet; if (BeginAnimateUpdate(info)) { ShowWindow(info->hWnd, SW_SHOW); PostMessage(info->hWnd, WM_CLOSE, 0, 0); PostMessage(hWnd, WM_CLOSE, 0, 0); bRet = DoAnimate(TRUE, ANIMTYPE_PREVIEW_FADE, info, TRUE); info->hSearchHWnd = NULL; } return bRet; } break; } case WM_LBUTTONUP: { ShowWindow(info->hWnd, SW_SHOW); PostMessage(info->hWnd, WM_CLOSE, 0, 0); PostMessage(hWnd, WM_CLOSE, 0, 0); break; } case WM_NCHITTEST: { int xPos = GET_X_LPARAM(lParam); int yPos = GET_Y_LPARAM(lParam); RECT rect = GetSearchRect(info); if (xPos >= rect.left && xPos <= rect.right && yPos >= rect.top && yPos <= rect.bottom) { //return HTTRANSPARENT; } else { //return HTCLIENT; } break; } case WM_ERASEBKGND: { PAINTSTRUCT ps; HDC hdc = BeginPaint(hWnd, &ps); HDC wallpaperHdc = GetDC(info->hWallpaperWnd); BitBlt( hdc, 0, 0, info->realArea.right - info->realArea.left, info->realArea.bottom - info->realArea.top, wallpaperHdc, info->realArea.left, info->realArea.top, SRCCOPY ); EndPaint(hWnd, &ps); return 1; break; } } return DefWindowProc(hWnd, uMsg, wParam, lParam); } LRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { MonitorInfo* info; if (uMsg == WM_CREATE) { CREATESTRUCT* pCreate = reinterpret_cast<CREATESTRUCT*>(lParam); info = reinterpret_cast<MonitorInfo*>(pCreate->lpCreateParams); SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR)info); HINSTANCE hInstance = pCreate->hInstance; } else { LONG_PTR ptr = GetWindowLongPtr(hWnd, GWLP_USERDATA); info = reinterpret_cast<MonitorInfo*>(ptr); } switch (uMsg) { /* case WM_ACTIVATE: { if (wParam == WA_INACTIVE) { BOOL isOneInSearch = FALSE; BOOL isOurFocused = FALSE; HWND fWnd = GetForegroundWindow(); for (UINT z = 0; z < monitors.size(); ++z) { if (monitors.at(z).hSearchHWnd != NULL) { isOneInSearch = TRUE; } if (monitors.at(z).hWnd == fWnd) { isOurFocused = TRUE; } } if (!isOneInSearch && !isOurFocused) { for (UINT z = 0; z < monitors.size(); ++z) { DoAnimate(FALSE, ANIMTYPE_PREVIEW, &monitors.at(z), FALSE); } } } } */ case WM_NCHITTEST: { int xPos = GET_X_LPARAM(lParam); int yPos = GET_Y_LPARAM(lParam); if (xPos < 10 && yPos < 10) { return HTCAPTION; } break; } case WM_CLOSE: if (wParam == 99) { HANDLE myself; myself = OpenProcess(PROCESS_ALL_ACCESS, false, GetCurrentProcessId()); TerminateProcess(myself, 0); return TRUE; } if (info->hSearchHWnd == NULL) { BOOL isOneInSearch = FALSE; for (UINT z = 0; z < monitors.size(); ++z) { if (monitors.at(z).hSearchHWnd != NULL) { isOneInSearch = TRUE; } } if (!isOneInSearch && wParam != 3) { SetForegroundWindow(previous); } if (wParam == 3) { return DoAnimate(FALSE, ANIMTYPE_MAIN_FADE, info, FALSE); } if (info->focusHWnd == hWnd || wParam == 2 || !isOneInSearch) { return DoAnimate(FALSE, ANIMTYPE_PREVIEW, info, FALSE); } return 0; } else { LONG styles = GetWindowLong(info->hWnd, GWL_EXSTYLE); styles &= ~WS_EX_TRANSPARENT; SetWindowLong(info->hWnd, GWL_EXSTYLE, styles); SetWindowPos(info->hWnd, 0, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE); if (!wParam) { // Esc or mouse pressed when searching BOOL bRet; if (BeginAnimateUpdate(info)) { //DwmUnregisterThumbnail(info->hSearchThumb); //info->hSearchThumb = NULL; bRet = DoAnimate(TRUE, ANIMTYPE_PREVIEW_FADE, info, TRUE); SetForegroundWindow(hWnd); PostMessage(info->hSearchHWnd, WM_CLOSE, 0, 0); SetWindowPos( info->hSearchHWnd, info->hSearchHWnd, info->rcSearch.left, info->rcSearch.top, 0, 0, SWP_NOZORDER | SWP_NOSIZE ); info->hSearchHWnd = NULL; } return bRet; } else { // Return pressed when searching BOOL bRet = DoAnimate(FALSE, ANIMTYPE_MAIN_FADE, info, FALSE); for (UINT z = 0; z < monitors.size(); ++z) { // semaphore protects us DoAnimate(FALSE, ANIMTYPE_PREVIEW, &monitors.at(z), FALSE); } return bRet; } } break; case WM_DESTROY: PostQuitMessage(0); break; case WM_WINDOWPOSCHANGING: return 0; case WM_ERASEBKGND: { PAINTSTRUCT ps; HDC hdc = BeginPaint(hWnd, &ps); HDC wallpaperHdc = GetDC(info->hWallpaperWnd); BitBlt( hdc, 0, 0, info->realArea.right - info->realArea.left, info->realArea.bottom - info->realArea.top, wallpaperHdc, info->realArea.left - info->wallpaperOffset->cx, info->realArea.top - info->wallpaperOffset->cy, SRCCOPY ); EndPaint(hWnd, &ps); return 1; break; } case WM_THREAD_DONE: CloseHandle(info->hAnimThread); info->hAnimThread = NULL; if (!info->animation.isOpening) { switch (info->animation.type) { case ANIMTYPE_MAIN_FADE: case ANIMTYPE_PREVIEW: { EndAnimateUpdate(info); HANDLE myself; myself = OpenProcess(PROCESS_ALL_ACCESS, false, GetCurrentProcessId()); TerminateProcess(myself, 0); return TRUE; break; } case ANIMTYPE_PREVIEW_FADE: { ShowWindow(info->hWnd, SW_HIDE); //PostMessage(h, WM_CLOSE, 0, 0); //RECT rect = GetSearchRect(info); //info->hSearchThumb = RegisterLiveThumbnail( // hWnd, info->hSearchHWnd, rect // ); EndAnimateUpdate(info); return TRUE; break; } } } else { // fix for window not getting back foreground from Search or when opening switch (info->animation.type) { case ANIMTYPE_PREVIEW: case ANIMTYPE_PREVIEW_FADE: if (GetForegroundWindow() != hWnd && hWnd == info->focusHWnd) { auto h = CreateWindowEx( WS_EX_TOPMOST | WS_EX_TOOLWINDOW, CLASS_NAME_SIMPLE, NULL, WS_POPUP, info->area.left, info->area.top, 10, 10, NULL, NULL, NULL, info ); ShowWindow(h, SW_NORMAL); PostMessage(h, WM_CLOSE, 0, 0); } break; } } EndAnimateUpdate(info); printf("%d\n", GetForegroundWindow()); break; case WM_KEYUP: { if (wParam == VK_ESCAPE) { PostMessage(hWnd, WM_CLOSE, 0, 0); } break; } case WM_KEYDOWN: { if (((wParam >= 'a' && wParam <= 'z') || (wParam >= 'A' && wParam <= 'Z') || (wParam >= '0' && wParam <= '9') || (wParam >= VK_NUMPAD0 && wParam <= VK_NUMPAD9) || wParam == VK_SPACE) && fwndHook == NULL) { if (BeginAnimateUpdate(info)) { mainHwnd = hWnd; fwndHook = SetWinEventHook( EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, NULL, DetectSearchDismiss, 0, 0, WINEVENT_OUTOFCONTEXT ); bkgHwnd = CreateWindowEx( WS_EX_TOOLWINDOW, CLASS_NAME_BKG, NULL, WS_POPUP, info->realArea.left, info->realArea.top, info->realArea.right - info->realArea.left, info->realArea.bottom - info->realArea.top, NULL, NULL, NULL, info ); ShowWindow(bkgHwnd, SW_NORMAL); ShowSearch(info, wParam); } } break; } case WM_SHOW_SEARCH: { if (BeginAnimateUpdate(info)) { ShowSearch(info, wParam); } break; } case WM_IS_SEARCH: { return info->hSearchHWnd != NULL; } case WM_ASK_MOUSE: { RECT rect = GetSearchRect(info); int xPos = GET_X_LPARAM(lParam); int yPos = GET_Y_LPARAM(lParam); if (info->focusHWnd == hWnd) { BOOL isInside = FALSE; for (UINT z = 0; z < monitors.size(); ++z) { if (xPos >= monitors.at(z).realArea.left && xPos <= monitors.at(z).realArea.right && yPos >= monitors.at(z).realArea.top && yPos <= monitors.at(z).realArea.bottom) { isInside = TRUE; } } if (!isInside) { for (UINT z = 0; z < monitors.size(); ++z) { monitors.at(z).hSearchHWnd = NULL; PostMessage(monitors.at(z).hWnd, WM_CLOSE, 3, 0); } } } if (info->hSearchHWnd != NULL) // && xPos >= rect.left && xPos <= rect.right && yPos >= rect.top && yPos <= rect.bottom) { //printf("-> %d\n", wParam); if (xPos >= rect.left && xPos <= rect.right && yPos >= rect.top && yPos <= rect.bottom) { if (wParam && info->focusHWnd == hWnd) { HANDLE thread = CreateThread( NULL, 0, CheckSearch, reinterpret_cast<LPVOID>(info), 0, NULL ); CloseHandle(thread); } } else { LONG styles = GetWindowLong(hWnd, GWL_EXSTYLE); LONG new_styles = styles & ~WS_EX_TRANSPARENT; SetWindowLong(hWnd, GWL_EXSTYLE, new_styles); SetWindowPos(hWnd, 0, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE); PostMessage(hWnd, WM_CLOSE, 0, 0); } return TRUE; } return FALSE; break; } case WM_LBUTTONUP: { if (!wParam) { int xPos = GET_X_LPARAM(lParam); int yPos = GET_Y_LPARAM(lParam); if (info->hSearchHWnd == NULL) { if (BeginAnimateUpdate(info)) { BOOL bClickOk = FALSE; for (int i = 0; i < info->animation.animations.size(); ++i) { Animation* animation = &(info->animation.animations.at(i)); RECT rect = { 0,0,0,0 }; rect.left = animation->end.x - (animation->w * animation->scale) / 2; rect.top = animation->end.y - (animation->h * animation->scale) / 2; rect.right = (animation->w * animation->scale) + rect.left; rect.bottom = (animation->h * animation->scale) + rect.top; if (xPos >= rect.left && xPos <= rect.right && yPos >= rect.top && yPos <= rect.bottom) { DWORD myBand; pGetWindowBand(animation->hWnd, &myBand); DwmUnregisterThumbnail(animation->thumb); animation->thumb = RegisterLiveThumbnail(hWnd, animation->hWnd, rect); for (int j = 0; j < info->animation.animations.size(); ++j) { if (i != j) { DWORD band; pGetWindowBand(info->animation.animations.at(j).hWnd, &band); if (band > myBand) { DwmUnregisterThumbnail(info->animation.animations.at(j).thumb); info->animation.animations.at(j).thumb = RegisterLiveThumbnail(hWnd, info->animation.animations.at(j).hWnd, rect); } } } SetForegroundWindow(animation->hWnd); DoAnimate(TRUE, ANIMTYPE_PREVIEW, info, FALSE); for (UINT z = 0; z < monitors.size(); ++z) { // we are protected by the semaphore DoAnimate(FALSE, ANIMTYPE_PREVIEW, &monitors.at(z), FALSE); } bClickOk = TRUE; break; } } if (!bClickOk) { SetForegroundWindow(previous); DoAnimate(TRUE, ANIMTYPE_PREVIEW, info, FALSE); for (UINT z = 0; z < monitors.size(); ++z) { DoAnimate(FALSE, ANIMTYPE_PREVIEW, &monitors.at(z), FALSE); } } } } else { RECT rect = GetSearchRect(info); if (!(xPos >= rect.left && xPos <= rect.right && yPos >= rect.top && yPos <= rect.bottom)) { if (BeginAnimateUpdate(info)) { //DwmUnregisterThumbnail(info->hSearchThumb); //info->hSearchThumb = NULL; DoAnimate(TRUE, ANIMTYPE_PREVIEW_FADE, info, TRUE); SetForegroundWindow(hWnd); PostMessage(info->hSearchHWnd, WM_CLOSE, 0, 0); SetWindowPos( info->hSearchHWnd, info->hSearchHWnd, info->rcSearch.left, info->rcSearch.top, 0, 0, SWP_NOZORDER | SWP_NOSIZE ); info->hSearchHWnd = NULL; } } } } break; } default: break; } return DefWindowProc(hWnd, uMsg, wParam, lParam); } BOOL running = FALSE; HWND CreateWin(RECT rect, LPVOID info) { if (hpath == NULL) { hpath = LoadLibrary(L"user32.dll"); pCreateWindowInBand = CreateWindowInBand(GetProcAddress(hpath, "CreateWindowInBand")); pGetWindowBand = GetWindowBand(GetProcAddress(hpath, "GetWindowBand")); pSetWindowBand = SetWindowBand(GetProcAddress(hpath, "SetWindowBand")); } auto hwndParent = pCreateWindowInBand( WS_EX_TOPMOST | WS_EX_LAYERED,// | WS_EX_NOREDIRECTIONBITMAP, parentWindowClass, NULL, WS_POPUP, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, NULL, NULL, NULL, info, ZBID_LOCK ); SetLayeredWindowAttributes(hwndParent, 0, 255, LWA_ALPHA); const pfnSetWindowCompositionAttribute SetWindowCompositionAttribute = (pfnSetWindowCompositionAttribute)GetProcAddress(hpath, "SetWindowCompositionAttribute"); if (SetWindowCompositionAttribute) { ACCENT_POLICY accent = { ACCENT_ENABLE_BLURBEHIND, 0, 0xCC000000, 0 }; WINDOWCOMPOSITIONATTRIBDATA data; data.Attrib = WCA_ACCENT_POLICY; data.pvData = &accent; data.cbData = sizeof(accent); //SetWindowCompositionAttribute(hwndParent, &data); } return hwndParent; } __declspec(dllexport) DWORD WINAPI main(LPVOID lpParam) { if (running) { return 0; } running = TRUE; previous = GetForegroundWindow(); /* FILE* conout; if (!AllocConsole()) { } if (freopen_s(&conout, "CONOUT$", "w", stdout)) { } */ WNDCLASSEX wndParentClass = {}; wndParentClass.cbSize = sizeof(WNDCLASSEX); wndParentClass.cbClsExtra = 0; wndParentClass.hIcon = NULL; wndParentClass.lpszMenuName = NULL; wndParentClass.hIconSm = NULL; wndParentClass.lpfnWndProc = WindowProc; wndParentClass.hInstance = NULL; wndParentClass.hCursor = LoadCursor(0, IDC_ARROW); wndParentClass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); wndParentClass.lpszClassName = CLASS_NAME; parentWindowClass = RegisterClassEx(&wndParentClass); WNDCLASSEX wndParentClass2 = {}; wndParentClass2.cbSize = sizeof(WNDCLASSEX); wndParentClass2.cbClsExtra = 0; wndParentClass2.hIcon = NULL; wndParentClass2.lpszMenuName = NULL; wndParentClass2.hIconSm = NULL; wndParentClass2.lpfnWndProc = SimpleWindowProc; wndParentClass2.hInstance = NULL; wndParentClass2.hCursor = LoadCursor(0, IDC_ARROW); wndParentClass2.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); wndParentClass2.lpszClassName = CLASS_NAME_SIMPLE; simpleWindowClass = RegisterClassEx(&wndParentClass2); WNDCLASSEX wndParentClass3 = {}; wndParentClass3.cbSize = sizeof(WNDCLASSEX); wndParentClass3.cbClsExtra = 0; wndParentClass3.hIcon = NULL; wndParentClass3.lpszMenuName = NULL; wndParentClass3.hIconSm = NULL; wndParentClass3.lpfnWndProc = WindowProcBkg; wndParentClass3.hInstance = NULL; wndParentClass3.hCursor = LoadCursor(0, IDC_ARROW); wndParentClass3.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); wndParentClass3.lpszClassName = CLASS_NAME_BKG; bkgWindowClass = RegisterClassEx(&wndParentClass3); SIZE_T monitorNo, slotNo; BOOL atLeastOneWindow = FALSE; GetMonitors(&monitors); for (monitorNo = 0; monitorNo < monitors.size(); ++monitorNo) { monitors.at(monitorNo).realArea = monitors.at(monitorNo).rcWork; monitors.at(monitorNo).area = monitors.at(monitorNo).rcWork; // normalize area - move its origin to (0, 0) as we use these for displaying inside the window, // whose origin is always at (0, 0) no matter its physical coordinates (where it is on the displays) monitors.at(monitorNo).area.right -= monitors.at(monitorNo).area.left + AREA_BORDER * 2; monitors.at(monitorNo).area.bottom -= monitors.at(monitorNo).area.top + AREA_BORDER * 2; monitors.at(monitorNo).area.left = 0 + AREA_BORDER; monitors.at(monitorNo).area.top = 0 + AREA_BORDER; std::vector<WindowInfo> windows; GetWindowsOnMonitor(monitors.at(monitorNo), &windows); if (windows.size() == 0) { RECT r; r.left = 0; r.right = 0; r.right = 0; r.bottom = 0; monitors.at(monitorNo).realArea = r; continue; } atLeastOneWindow = TRUE; std::vector<Slot> slots; GetWindowSlots(&windows, monitors.at(monitorNo).area, &slots); sort(slots.begin(), slots.end(), SortSlotsByHwndZOrder); monitors.at(monitorNo).hWnd = CreateWin( monitors.at(monitorNo).realArea, &monitors.at(monitorNo) ); InitializeAnimation( &monitors.at(monitorNo) ); if (BeginAnimateUpdate(&monitors.at(monitorNo))) { for (slotNo = 0; slotNo < slots.size(); ++slotNo) { RECT initialRect; RECT finalRect; POINT initialCentre; POINT finalCentre; ComputeSlotCoordinates( slots.at(slotNo).window.hwnd, slots.at(slotNo).x, slots.at(slotNo).y, slots.at(slotNo).scale, monitors.at(monitorNo).realArea, monitors.at(monitorNo).area, &initialRect, &finalRect, &initialCentre, &finalCentre ); AddAnimation( monitors.at(monitorNo).animation, initialCentre, finalCentre, initialRect, finalRect, slots.at(slotNo).scale, slots.at(slotNo).window.hwnd, RegisterLiveThumbnail( monitors.at(monitorNo).hWnd, slots.at(slotNo).window.hwnd, initialRect ) ); } EndAnimateUpdate(&monitors.at(monitorNo)); } printf("%d, windows size: %d\n", monitorNo, windows.size()); /* monitors.at(monitorNo).bkgHWnd = pCreateWindowInBand( WS_EX_TOPMOST | WS_EX_LAYERED, bkgWindowClass, NULL, WS_POPUP, monitors.at(monitorNo).area.left, monitors.at(monitorNo).area.top, monitors.at(monitorNo).area.right - monitors.at(monitorNo).area.left, monitors.at(monitorNo).area.bottom - monitors.at(monitorNo).area.top, NULL, NULL, NULL, &monitors.at(monitorNo), ZBID_IMMERSIVE_APPCHROME ); SetLayeredWindowAttributes(monitors.at(monitorNo).bkgHWnd, 0, 255, LWA_ALPHA); ShowWindow(monitors.at(monitorNo).bkgHWnd, SW_SHOWNORMAL); */ } UINT uIndex; POINT pCur; GetCursorPos(&pCur); HMONITOR hMon = MonitorFromPoint(pCur, MONITOR_DEFAULTTONULL); for (UINT z = 0; z < monitors.size(); ++z) { if (monitors.at(z).hMonitor == hMon) { uIndex = z; } else { if (monitors.at(z).hWnd) { DoAnimate(FALSE, ANIMTYPE_PREVIEW, &monitors.at(z), TRUE); ShowWindow(monitors.at(z).hWnd, SW_SHOW); } } } monitors.at(uIndex).focusHWnd = monitors.at(uIndex).hWnd; if (monitors.at(uIndex).hWnd) { DoAnimate(FALSE, ANIMTYPE_PREVIEW, &monitors.at(uIndex), TRUE); ShowWindow(monitors.at(uIndex).hWnd, SW_SHOW); SetForegroundWindow(monitors.at(uIndex).hWnd); } for (UINT z = 0; z < monitors.size(); ++z) { monitors.at(z).focusHWnd = monitors.at(uIndex).hWnd; } if (!atLeastOneWindow) { INPUT ip; ip.type = INPUT_KEYBOARD; ip.ki.wScan = 0; ip.ki.time = 0; ip.ki.dwExtraInfo = 0; ip.ki.wVk = VK_LWIN; ip.ki.dwFlags = 0; SendInput(1, &ip, sizeof(INPUT)); ip.ki.wVk = 0x51; ip.ki.dwFlags = 0; SendInput(1, &ip, sizeof(INPUT)); ip.ki.wVk = 0x51; ip.ki.dwFlags = KEYEVENTF_KEYUP; SendInput(1, &ip, sizeof(INPUT)); ip.ki.wVk = VK_LWIN; ip.ki.dwFlags = KEYEVENTF_KEYUP; SendInput(1, &ip, sizeof(INPUT)); exit(0); } MSG msg; while (GetMessage(&msg, nullptr, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return 0; } BOOL APIENTRY DllMain( HINSTANCE hDllHandle, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: DisableThreadLibraryCalls(hDllHandle); break; case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; }
23,036
C++
.cpp
839
22.405244
210
0.648622
valinet/WinOverview
39
6
2
GPL-2.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,504
workspace.cpp
valinet_WinOverview/WinOverviewLibrary/workspace.cpp
#include "pch.h" #include <iostream> #include <Windows.h> #include <algorithm> #include "constants.h" #include "structs.h" #include "workspace.h" #include "helpers.h" // Window layout logic converted from the official GNOME Activities JavaScript code // Available at: https://gitlab.gnome.org/GNOME/gnome-shell/-/blob/master/js/ui/workspace.js static inline double interpolate(double start, double end, double step) { return start + (end - start) * step; } static inline double computeWindowScale(WindowInfo window, RECT area) { double ratio = (window.rect.bottom - window.rect.top) / ((area.bottom - area.top) * 1.0); double res = interpolate(2.5, 1, ratio); return res; } static void computeRowSizes(Layout* layout) { for (int i = 0; i < layout->rows.size(); ++i) { Row& row = layout->rows.at(i); row.width = row.fullWidth * layout->scale + (row.windows.size() - 1) * _columnSpacing; row.height = row.fullHeight * layout->scale; } } void computeWindowSlots(Layout* layout, RECT area, std::vector<Slot>* slots) { computeRowSizes(layout); std::vector<Row>& rows = layout->rows; double& scale = layout->scale; // Do this in three parts. int heightWithoutSpacing = 0; for (int i = 0; i < rows.size(); i++) { Row& row = rows.at(i); heightWithoutSpacing += row.height; } int verticalSpacing = (rows.size() - 1) * _rowSpacing; double additionalVerticalScale = min(1, ((area.bottom - area.top) - verticalSpacing) / heightWithoutSpacing); // keep track how much smaller the grid becomes due to scaling // so it can be centered again double compensation = 0; double y = 0; for (int i = 0; i < rows.size(); ++i) { Row& row = rows.at(i); // If this window layout row doesn't fit in the actual // geometry, then apply an additional scale to it. int horizontalSpacing = (row.windows.size() - 1) * _columnSpacing; int widthWithoutSpacing = row.width - horizontalSpacing; double additionalHorizontalScale = min(1, ((area.right - area.left) - horizontalSpacing) / widthWithoutSpacing); if (additionalHorizontalScale < additionalVerticalScale) { row.additionalScale = additionalHorizontalScale; // Only consider the scaling in addition to the vertical scaling for centering. compensation += (additionalVerticalScale - additionalHorizontalScale) * row.height; } else { row.additionalScale = additionalVerticalScale; // No compensation when scaling vertically since centering based on a too large // height would undo what vertical scaling is trying to achieve. } row.x = area.left + (max((area.right - area.left) - (widthWithoutSpacing * row.additionalScale + horizontalSpacing), 0) / 2); row.y = area.top + (max((area.bottom - area.top) - (heightWithoutSpacing + verticalSpacing), 0) / 2) + y; y += row.height * row.additionalScale + _rowSpacing; } compensation /= 2; for (int i = 0; i < rows.size(); ++i) { Row& row = rows.at(i); double x = row.x; for (int j = 0; j < row.windows.size(); ++j) { WindowInfo& window = row.windows.at(j); double s = scale * computeWindowScale(window, area) * row.additionalScale; double cellWidth = (window.rect.right - window.rect.left) * s; double cellHeight = (window.rect.bottom - window.rect.top) * s; s = min(s, WINDOW_CLONE_MAXIMUM_SCALE); double cloneWidth = (window.rect.right - window.rect.left) * s; double cloneX = x + (cellWidth - cloneWidth) / 2; double cloneY = row.y + row.height * row.additionalScale - cellHeight + compensation; // Align with the pixel grid to prevent blurry windows at scale = 1 cloneX = floor(cloneX); cloneY = floor(cloneY); Slot slot; slot.x = cloneX; slot.y = cloneY; slot.scale = s; slot.window = window; slots->push_back(slot); x += cellWidth + _columnSpacing; } } } bool isBetterLayout(Layout* oldLayout, Layout* newLayout) { if (oldLayout->scale == -1) return true; double spacePower = (newLayout->space - oldLayout->space) * LAYOUT_SPACE_WEIGHT; double scalePower = (newLayout->scale - oldLayout->scale) * LAYOUT_SCALE_WEIGHT; if (newLayout->scale > oldLayout->scale && newLayout->space > oldLayout->space) { // Win win -- better scale and better space return true; } else if (newLayout->scale > oldLayout->scale && newLayout->space <= oldLayout->space) { // Keep new layout only if scale gain outweighs aspect space loss return scalePower > spacePower; } else if (newLayout->scale <= oldLayout->scale && newLayout->space > oldLayout->space) { // Keep new layout only if aspect space gain outweighs scale loss return spacePower > scalePower; } else { // Lose -- worse scale and space return false; } } void computeScaleAndSpace(Layout* layout, RECT area) { double hspacing = (layout->maxColumns - 1) * _columnSpacing; double vspacing = (layout->numRows - 1) * _rowSpacing; double spacedWidth = (area.right - area.left) - hspacing; double spacedHeight = (area.bottom - area.top) - vspacing; double horizontalScale = spacedWidth / layout->gridWidth; double verticalScale = spacedHeight / layout->gridHeight; // Thumbnails should be less than 70% of the original size double scale = min(horizontalScale, verticalScale, 1.0); double scaledLayoutWidth = layout->gridWidth * scale + hspacing; double scaledLayoutHeight = layout->gridHeight * scale + vspacing; double space = (scaledLayoutWidth * scaledLayoutHeight) / ((area.right - area.left) * (area.bottom - area.top)); layout->scale = scale; layout->space = space; } static inline bool keepSameRow(Row row, WindowInfo window, double width, double idealRowWidth) { if (row.fullWidth + width <= idealRowWidth) return true; double oldRatio = 1.0 * row.fullWidth / idealRowWidth; double newRatio = 1.0 * (row.fullWidth + width) / idealRowWidth; if (abs(1.0 - newRatio) < abs(1.0 - oldRatio)) return true; return false; } static bool windowInfoSortVerticallyComparator(WindowInfo w1, WindowInfo w2) { int w1x = (w1.rect.right - w1.rect.left) / 2 + w1.rect.left; int w1y = (w1.rect.bottom - w1.rect.top) / 2 + w1.rect.top; int w2x = (w2.rect.right - w2.rect.left) / 2 + w2.rect.left; int w2y = (w2.rect.bottom - w2.rect.top) / 2 + w2.rect.top; return w1y < w2y; } static bool windowInfoSortHorizontallyComparator(WindowInfo w1, WindowInfo w2) { int w1x = (w1.rect.right - w1.rect.left) / 2 + w1.rect.left; int w1y = (w1.rect.bottom - w1.rect.top) / 2 + w1.rect.top; int w2x = (w2.rect.right - w2.rect.left) / 2 + w2.rect.left; int w2y = (w2.rect.bottom - w2.rect.top) / 2 + w2.rect.top; return w1x < w2x; } bool SortSlotsByHwndZOrder(Slot s1, Slot s2) { return SortHwndByZorder(s1.window.hwnd, s2.window.hwnd); } void computeLayout(std::vector<WindowInfo>* windows, Layout* layout, RECT area) { Row nullRow; nullRow.exists = false; int numRows = layout->numRows; std::vector<Row>& rows = layout->rows; double totalWidth = 0; for (int i = 0; i < windows->size(); ++i) { WindowInfo window = windows->at(i); double s = computeWindowScale(window, area); totalWidth += (window.rect.right - window.rect.left) * s; } double idealRowWidth = totalWidth / numRows; // Sort windows vertically to minimize travel distance. // This affects what rows the windows get placed in. std::vector<WindowInfo> sortedWindows(*windows); std::sort(sortedWindows.begin(), sortedWindows.end(), windowInfoSortVerticallyComparator); int windowIdx = 0; for (int i = 0; i < numRows; ++i) { Row _row; _row.exists = true; _row.fullHeight = 0; _row.fullWidth = 0; _row.width = 0; _row.height = 0; rows.push_back(_row); Row& row = rows.at(rows.size() - 1); for (; windowIdx < sortedWindows.size(); ++windowIdx) { WindowInfo window = sortedWindows.at(windowIdx); double s = computeWindowScale(window, area); double width = (window.rect.right - window.rect.left) * s; double height = (window.rect.bottom - window.rect.top) * s; row.fullHeight = max(row.fullHeight, height); if (keepSameRow(row, window, width, idealRowWidth) || (i == numRows - 1)) { row.windows.push_back(window); row.fullWidth += width; } else { break; } } } int gridHeight = 0; Row& maxRow = nullRow; for (int i = 0; i < numRows; ++i) { Row& row = rows.at(i); sort(row.windows.begin(), row.windows.end(), windowInfoSortHorizontallyComparator); if (!maxRow.exists || row.fullWidth > maxRow.fullWidth) maxRow = row; gridHeight += row.fullHeight; } layout->maxColumns = maxRow.windows.size(); layout->gridWidth = maxRow.fullWidth; layout->gridHeight = gridHeight; }
9,730
C++
.cpp
209
38.220096
134
0.626008
valinet/WinOverview
39
6
2
GPL-2.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,505
WinOverview.cpp
valinet_WinOverview/WinOverview/WinOverview.cpp
#include <iostream> #include <conio.h> #include <Windows.h> #include <shlwapi.h> #include <Psapi.h> #include <tlhelp32.h> #include <assert.h> #include <sddl.h> #pragma comment(lib, "Shlwapi.lib") #include "../WinOverviewLibrary/constants.h" #include "NtUserBuildHwndList.h" HMODULE hKernel32 = NULL; FARPROC hAdrWinExec = NULL; BOOL running = FALSE; DWORD lastKey = NULL; HHOOK keyboardHook = NULL; HHOOK mouseHook = NULL; NtUserBuildHwndList pNtUserBuildHwndList = NULL; DWORD WINAPI run(LPVOID lpParam) { HANDLE hThread = NULL; BOOL bResult = FALSE; void* pLibRemote = NULL; DWORD hLibModule = 0; char szHostPath[_MAX_PATH + 2 * sizeof(char)]; PROCESSENTRY32 entry; entry.dwSize = sizeof(PROCESSENTRY32); HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL); if (Process32First(snapshot, &entry) == TRUE) { while (Process32Next(snapshot, &entry) == TRUE) { if (!wcscmp(entry.szExeFile, L"explorer.exe")) { HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID); if (hProcess) { GetModuleFileNameA( GetModuleHandle(NULL), szHostPath + sizeof(char), _MAX_PATH ); PathRemoveFileSpecA(szHostPath + sizeof(char)); szHostPath[0] = '\"'; strcat_s( szHostPath, "\\WinOverviewLauncher.exe\"" ); pLibRemote = VirtualAllocEx( hProcess, NULL, sizeof(szHostPath), MEM_COMMIT, PAGE_READWRITE ); assert(pLibRemote != NULL); bResult = WriteProcessMemory( hProcess, pLibRemote, (void*)szHostPath, sizeof(szHostPath), NULL ); assert(bResult == TRUE); hThread = CreateRemoteThread( hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)hAdrWinExec, pLibRemote, CREATE_SUSPENDED, NULL ); assert(hThread != NULL); ResumeThread( hThread ); WaitForSingleObject( hThread, INFINITE ); GetExitCodeThread( hThread, &hLibModule ); UnhookWindowsHookEx(mouseHook); mouseHook = NULL; //printf("WinExec: %d\n", hLibModule); VirtualFreeEx( hProcess, (LPVOID)pLibRemote, 0, MEM_RELEASE ); CloseHandle(hProcess); break; } } } } CloseHandle(snapshot); running = FALSE; return 0; } BOOL CALLBACK EnumWindowsSendMessage( _In_ HWND hwnd, _In_ LPARAM lParam ) { TCHAR name[200]; GetClassName(hwnd, name, 200); if (!wcscmp(name, CLASS_NAME)) { SendMessage(hwnd, WM_CLOSE, lParam, 0); } return TRUE; } DWORD WINAPI EnumWindowsSendMessageThread( _In_ LPVOID lpParam ) { Gui_RealEnumWindows(pNtUserBuildHwndList, EnumWindowsSendMessage, reinterpret_cast<LPARAM>(lpParam)); return 0; } BOOL CALLBACK EnumWindowsAskMouse( _In_ HWND hwnd, _In_ LPARAM lParam ) { TCHAR name[200]; GetClassName(hwnd, name, 200); if (!wcscmp(name, CLASS_NAME)) { MSLLHOOKSTRUCT* info = reinterpret_cast<MSLLHOOKSTRUCT*>(lParam); SendMessage(hwnd, WM_ASK_MOUSE, TRUE, MAKELPARAM(info->pt.x, info->pt.y)); } return TRUE; } DWORD WINAPI EnumWindowsAskMouseThread( _In_ LPVOID lpParam ) { Gui_RealEnumWindows(pNtUserBuildHwndList, EnumWindowsAskMouse, reinterpret_cast<LPARAM>(lpParam)); return 0; } LRESULT CALLBACK LowLevelMouseProc( _In_ int nCode, _In_ WPARAM wParam, _In_ LPARAM lParam ) { if (running) { if (wParam == WM_LBUTTONUP || wParam == WM_RBUTTONUP) { CreateThread(NULL, 0, EnumWindowsAskMouseThread, reinterpret_cast<LPVOID>(lParam), 0, NULL); } } return CallNextHookEx(NULL, nCode, wParam, lParam); } LRESULT CALLBACK LowLevelKeyboardProc( _In_ int nCode, _In_ WPARAM wParam, _In_ LPARAM lParam ) { if (nCode == HC_ACTION) { if (wParam == WM_KEYDOWN) { KBDLLHOOKSTRUCT* state = reinterpret_cast<KBDLLHOOKSTRUCT*>(lParam); printf("%d\n", state->vkCode); if (state->vkCode == VK_LWIN || state->vkCode == VK_RWIN || state->vkCode == VK_ESCAPE) { printf("keydown "); printf("running: %d\n", running); lastKey = VK_LWIN; } else { lastKey = NULL; } } if (wParam == WM_KEYUP) { KBDLLHOOKSTRUCT* state = reinterpret_cast<KBDLLHOOKSTRUCT*>(lParam); if ((state->vkCode == VK_RETURN) && running) { CreateThread(NULL, 0, EnumWindowsSendMessageThread, reinterpret_cast<LPVOID>(1), 0, NULL); } if ((state->vkCode == VK_LWIN || state->vkCode == VK_RWIN || state->vkCode == VK_ESCAPE) && lastKey == VK_LWIN) { printf("keyup "); printf("%d ", GetTickCount64()); printf("running: %d\n", running); lastKey = NULL; if (!running) { if (state->vkCode != VK_ESCAPE) { running = TRUE; CreateThread(0, 0, (LPTHREAD_START_ROUTINE)run, NULL, 0, 0); printf("CreateThread running: %d\n", running); mouseHook = SetWindowsHookEx( WH_MOUSE_LL, LowLevelMouseProc, NULL, 0 ); } } else { CreateThread(NULL, 0, EnumWindowsSendMessageThread, reinterpret_cast<LPVOID>(0), 0, NULL); } if (state->vkCode != VK_ESCAPE) { INPUT ip; ip.type = INPUT_KEYBOARD; ip.ki.wScan = 0; ip.ki.time = 0; ip.ki.dwExtraInfo = 0; ip.ki.wVk = VK_CONTROL; ip.ki.dwFlags = 0; SendInput(1, &ip, sizeof(INPUT)); ip.ki.wVk = VK_CONTROL; ip.ki.dwFlags = KEYEVENTF_KEYUP; SendInput(1, &ip, sizeof(INPUT)); } } } } return CallNextHookEx(NULL, nCode, wParam, lParam); } int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR pCmdLine, int nCmdShow) { /* FILE* conout; if (!AllocConsole()) { } if (freopen_s(&conout, "CONOUT$", "w", stdout)) { } */ HMODULE hpath; hpath = LoadLibrary(L"win32u.dll"); pNtUserBuildHwndList = NtUserBuildHwndList(GetProcAddress(hpath, "NtUserBuildHwndList")); hKernel32 = GetModuleHandle(L"Kernel32"); assert(hKernel32 != NULL); hAdrWinExec = GetProcAddress( hKernel32, "WinExec" ); assert(hAdrWinExec != NULL); int argc; LocalFree(CommandLineToArgvW(GetCommandLineW(), &argc)); if (argc > 1) { run(NULL); exit(0); } keyboardHook = SetWindowsHookEx( WH_KEYBOARD_LL, LowLevelKeyboardProc, NULL, 0 ); MSG msg = { }; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return 0; }
8,929
C++
.cpp
276
19.206522
124
0.472158
valinet/WinOverview
39
6
2
GPL-2.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,506
WinOverviewLauncher.cpp
valinet_WinOverview/WinOverviewLauncher/WinOverviewLauncher.cpp
#include <iostream> #include <conio.h> #include <Windows.h> #include <shlwapi.h> #include <Psapi.h> #include <tlhelp32.h> #include <assert.h> #include <sddl.h> #pragma comment(lib, "Shlwapi.lib") #include "../WinOverviewLibrary/constants.h" #include "../WinOverview/NtUserBuildHwndList.h" NtUserBuildHwndList pNtUserBuildHwndList = NULL; BOOL alreadyRunning = FALSE; BOOL CALLBACK EnumWindowsSendMessage( _In_ HWND hwnd, _In_ LPARAM lParam ) { TCHAR name[200]; GetClassName(hwnd, name, 200); if (!wcscmp(name, CLASS_NAME)) { SendMessage(hwnd, WM_CLOSE, lParam, 0); alreadyRunning = TRUE; } return TRUE; } int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR pCmdLine, int nCmdShow) { FILE* conout; wchar_t szHostPath[_MAX_PATH]; wchar_t szLibPath[_MAX_PATH]; HANDLE hThread = NULL; void* pLibRemote = NULL; DWORD hLibModule = 0; HMODULE hKernel32 = NULL; BOOL bResult = FALSE; FARPROC hAdrLoadLibrary = NULL; HANDLE hJob; JOBOBJECT_BASIC_LIMIT_INFORMATION jobInfoBasic; JOBOBJECT_EXTENDED_LIMIT_INFORMATION jobInfo; HMODULE hMods[1024]; DWORD cbNeeded; unsigned int i; HMODULE hInjectionDll; FARPROC hInjectionMainFunc; HMODULE hpath; /* if (!AllocConsole()) { } if (freopen_s(&conout, "CONOUT$", "w", stdout)) { } */ bResult = SetProcessDpiAwarenessContext( DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 ); hpath = LoadLibrary(L"win32u.dll"); pNtUserBuildHwndList = NtUserBuildHwndList(GetProcAddress(hpath, "NtUserBuildHwndList")); Gui_RealEnumWindows(pNtUserBuildHwndList, EnumWindowsSendMessage, reinterpret_cast<LPARAM>(reinterpret_cast<LPVOID>(0))); if (alreadyRunning) exit(0); GetSystemDirectory( szHostPath, _MAX_PATH ); lstrcat( szHostPath, L"\\RuntimeBroker.exe" ); STARTUPINFO info = { sizeof(info) }; PROCESS_INFORMATION processInfo; bResult = CreateProcess( //hChildToken, NULL, szHostPath, NULL, NULL, TRUE, 0, NULL, NULL, &info, &processInfo ); assert(bResult != 0); assert(processInfo.hProcess != NULL); hJob = CreateJobObject( NULL, NULL ); jobInfoBasic.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; jobInfo.BasicLimitInformation = jobInfoBasic; SetInformationJobObject( hJob, JobObjectExtendedLimitInformation, &jobInfo, sizeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION) ); AssignProcessToJobObject( hJob, processInfo.hProcess ); GetModuleFileName( GetModuleHandle(NULL), szLibPath, _MAX_PATH ); PathRemoveFileSpec(szLibPath); lstrcat( szLibPath, L"\\WinOverview.dll" ); hKernel32 = GetModuleHandle(L"Kernel32"); assert(hKernel32 != NULL); hAdrLoadLibrary = GetProcAddress( hKernel32, "LoadLibraryW" ); assert(hAdrLoadLibrary != NULL); pLibRemote = VirtualAllocEx( processInfo.hProcess, NULL, sizeof(szLibPath), MEM_COMMIT, PAGE_READWRITE ); assert(pLibRemote != NULL); bResult = WriteProcessMemory( processInfo.hProcess, pLibRemote, (void*)szLibPath, sizeof(szLibPath), NULL ); assert(bResult == TRUE); hThread = CreateRemoteThread( processInfo.hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)hAdrLoadLibrary, pLibRemote, 0, NULL ); assert(hThread != NULL); WaitForSingleObject( hThread, INFINITE ); GetExitCodeThread( hThread, &hLibModule ); //assert(hLibModule != NULL); wchar_t szTmpLibPath[_MAX_PATH]; hInjectionDll = LoadLibrary(szLibPath); hInjectionMainFunc = GetProcAddress( hInjectionDll, "main" ); CharLower(szLibPath); if (EnumProcessModules(processInfo.hProcess, hMods, sizeof(hMods), &cbNeeded)) { for (i = 0; i < (cbNeeded / sizeof(HMODULE)); i++) { TCHAR szModName[MAX_PATH]; GetModuleFileNameEx(processInfo.hProcess, hMods[i], szTmpLibPath, _MAX_PATH); CharLower(szTmpLibPath); if (!wcscmp(szTmpLibPath, szLibPath)) { break; } } } hThread = CreateRemoteThread( processInfo.hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)((uint64_t)hMods[i] + (uint64_t)hInjectionMainFunc - (uint64_t)hInjectionDll), NULL, 0, NULL ); assert(hThread != NULL); WaitForSingleObject( hThread, INFINITE ); GetExitCodeThread( hThread, &hLibModule ); VirtualFreeEx( processInfo.hProcess, (LPVOID)pLibRemote, 0, MEM_RELEASE ); WaitForSingleObject(processInfo.hProcess, INFINITE); CloseHandle(processInfo.hProcess); CloseHandle(processInfo.hThread); CloseHandle(hJob); return 0; }
5,513
C++
.cpp
204
19.083333
126
0.599279
valinet/WinOverview
39
6
2
GPL-2.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,507
workspace.h
valinet_WinOverview/WinOverviewLibrary/workspace.h
#pragma once #include <vector> #include "structs.h" struct Row { bool exists; int fullHeight; int fullWidth; std::vector<WindowInfo> windows; int width = 0; int height = 0; double additionalScale; int x; int y; }; struct Layout { int numRows; int numColumns; std::vector<Row> rows; int maxColumns; int gridWidth; int gridHeight; double scale; double space; }; struct Slot { int x; int y; double scale; WindowInfo window; }; void computeLayout( std::vector<WindowInfo>* windows, Layout* layout, RECT area ); void computeScaleAndSpace( Layout* layout, RECT area ); bool isBetterLayout( Layout* oldLayout, Layout* newLayout ); void computeWindowSlots( Layout* layout, RECT area, std::vector<Slot>* slots ); bool SortSlotsByHwndZOrder( Slot s1, Slot s2 );
974
C++
.h
52
13.461538
39
0.62183
valinet/WinOverview
39
6
2
GPL-2.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,508
structs.h
valinet_WinOverview/WinOverviewLibrary/structs.h
#pragma once #include <Windows.h> #include <dwmapi.h> #include <vector> struct Animation { HWND hWnd; POINT start; POINT end; int w; int h; double scale; HTHUMBNAIL thumb; }; struct AnimationInfo { std::vector<Animation> animations; UINT type; double delay_ms; BOOL isOpening; }; struct MonitorInfo { HMONITOR hMonitor; RECT rcWork; RECT rcMonitor; RECT area; RECT realArea; RECT rcSearch; HWND hWallpaperWnd; HWND hWnd; HWND bkgHWnd; HWND focusHWnd; AnimationInfo animation; HANDLE hAnimMutex; HANDLE hAnimThread; HTHUMBNAIL hSearchThumb; HWND hSearchHWnd; SIZE* wallpaperOffset; }; struct WindowInfo { HWND hwnd; RECT rect; };
792
C++
.h
41
14.341463
39
0.655914
valinet/WinOverview
39
6
2
GPL-2.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,509
helpers.h
valinet_WinOverview/WinOverviewLibrary/helpers.h
#pragma once #include <Windows.h> #include <dwmapi.h> #include "workspace.h" enum ANIMTYPE { ANIMTYPE_PREVIEW = 0, ANIMTYPE_PREVIEW_FADE = 1, ANIMTYPE_MAIN_FADE = 2, }; enum ZBID { ZBID_DEFAULT = 0, ZBID_DESKTOP = 1, ZBID_UIACCESS = 2, ZBID_IMMERSIVE_IHM = 3, ZBID_IMMERSIVE_NOTIFICATION = 4, ZBID_IMMERSIVE_APPCHROME = 5, ZBID_IMMERSIVE_MOGO = 6, ZBID_IMMERSIVE_EDGY = 7, ZBID_IMMERSIVE_INACTIVEMOBODY = 8, ZBID_IMMERSIVE_INACTIVEDOCK = 9, ZBID_IMMERSIVE_ACTIVEMOBODY = 10, ZBID_IMMERSIVE_ACTIVEDOCK = 11, ZBID_IMMERSIVE_BACKGROUND = 12, ZBID_IMMERSIVE_SEARCH = 13, ZBID_GENUINE_WINDOWS = 14, ZBID_IMMERSIVE_RESTRICTED = 15, ZBID_SYSTEM_TOOLS = 16, ZBID_LOCK = 17, ZBID_ABOVELOCK_UX = 18, }; typedef HWND(WINAPI* CreateWindowInBand)( _In_ DWORD dwExStyle, _In_opt_ ATOM atom, _In_opt_ LPCWSTR lpWindowName, _In_ DWORD dwStyle, _In_ int X, _In_ int Y, _In_ int nWidth, _In_ int nHeight, _In_opt_ HWND hWndParent, _In_opt_ HMENU hMenu, _In_opt_ HINSTANCE hInstance, _In_opt_ LPVOID lpParam, DWORD band ); typedef BOOL(WINAPI* GetWindowBand)( _In_ HWND hWnd, _Out_ PDWORD pdwBand ); typedef BOOL(WINAPI* SetWindowBand)( _In_ HWND hWnd, _In_ HWND hWndInsertAfter, _In_ DWORD dwBand ); typedef enum _WINDOWCOMPOSITIONATTRIB { WCA_UNDEFINED = 0, WCA_NCRENDERING_ENABLED = 1, WCA_NCRENDERING_POLICY = 2, WCA_TRANSITIONS_FORCEDISABLED = 3, WCA_ALLOW_NCPAINT = 4, WCA_CAPTION_BUTTON_BOUNDS = 5, WCA_NONCLIENT_RTL_LAYOUT = 6, WCA_FORCE_ICONIC_REPRESENTATION = 7, WCA_EXTENDED_FRAME_BOUNDS = 8, WCA_HAS_ICONIC_BITMAP = 9, WCA_THEME_ATTRIBUTES = 10, WCA_NCRENDERING_EXILED = 11, WCA_NCADORNMENTINFO = 12, WCA_EXCLUDED_FROM_LIVEPREVIEW = 13, WCA_VIDEO_OVERLAY_ACTIVE = 14, WCA_FORCE_ACTIVEWINDOW_APPEARANCE = 15, WCA_DISALLOW_PEEK = 16, WCA_CLOAK = 17, WCA_CLOAKED = 18, WCA_ACCENT_POLICY = 19, WCA_FREEZE_REPRESENTATION = 20, WCA_EVER_UNCLOAKED = 21, WCA_VISUAL_OWNER = 22, WCA_HOLOGRAPHIC = 23, WCA_EXCLUDED_FROM_DDA = 24, WCA_PASSIVEUPDATEMODE = 25, WCA_USEDARKMODECOLORS = 26, WCA_LAST = 27 } WINDOWCOMPOSITIONATTRIB; typedef struct _WINDOWCOMPOSITIONATTRIBDATA { WINDOWCOMPOSITIONATTRIB Attrib; PVOID pvData; SIZE_T cbData; } WINDOWCOMPOSITIONATTRIBDATA; typedef enum _ACCENT_STATE { ACCENT_DISABLED = 0, ACCENT_ENABLE_GRADIENT = 1, ACCENT_ENABLE_TRANSPARENTGRADIENT = 2, ACCENT_ENABLE_BLURBEHIND = 3, ACCENT_ENABLE_ACRYLICBLURBEHIND = 4, // RS4 1803 ACCENT_ENABLE_HOSTBACKDROP = 5, // RS5 1809 ACCENT_INVALID_STATE = 6 } ACCENT_STATE; typedef struct _ACCENT_POLICY { ACCENT_STATE AccentState; DWORD AccentFlags; DWORD GradientColor; DWORD AnimationId; } ACCENT_POLICY; typedef BOOL(WINAPI* pfnGetWindowCompositionAttribute)(HWND, WINDOWCOMPOSITIONATTRIBDATA*); typedef BOOL(WINAPI* pfnSetWindowCompositionAttribute)(HWND, WINDOWCOMPOSITIONATTRIBDATA*); struct GetMonitorsParams { std::vector<MonitorInfo>* monitors; SIZE* offset; }; struct EnumWindowProcParam { std::vector<WindowInfo>* windows; MonitorInfo monitor; }; void GetMonitors( _Out_ std::vector<MonitorInfo>* monitors ); BOOL CALLBACK EnumDisplayMonitorsCallback( _In_ HMONITOR hMonitor, _In_ HDC hdcMonitor, _In_ LPRECT lprcMonitor, _Out_ LPARAM dwData ); BOOL IsAltTabWindow( _In_ HWND hwnd ); BOOL CALLBACK EnumWindowsProc( _In_ HWND hwnd, _Out_ LPARAM lParam ); void GetWindowsOnMonitor( _In_ MonitorInfo monitor, _Out_ std::vector<WindowInfo>* windows ); BOOL CALLBACK GetWallpaperHwnd( _In_ HWND hwnd, _Out_ LPARAM lParam ); void GetWallpaperWindows( _Inout_ std::vector<MonitorInfo>* monitors ); void GetWindowSlots( _In_ std::vector<WindowInfo>* windows, _In_ RECT area, _Out_ std::vector<Slot>* slots ); inline void ComputeSlotCoordinates( _In_ HWND hWnd, _In_ int x, _In_ int y, _In_ double scale, _In_ RECT realArea, _In_ RECT area, _Out_ RECT* initialRect, _Out_ RECT* finalRect, _Out_ POINT* initialCentre, _Out_ POINT* finalCentre ) { GetWindowRect(hWnd, initialRect); initialRect->right -= (realArea.left); initialRect->bottom -= (realArea.top); initialRect->left -= (realArea.left); initialRect->top -= (realArea.top); finalRect->left = area.left + x; finalRect->top = area.top + y; finalRect->right = ((initialRect->right - initialRect->left) * scale) + finalRect->left; finalRect->bottom = ((initialRect->bottom - initialRect->top) * scale) + finalRect->top; initialCentre->x = (initialRect->right - initialRect->left) / 2 + initialRect->left; initialCentre->y = (initialRect->bottom - initialRect->top) / 2 + initialRect->top; finalCentre->x = (finalRect->right - finalRect->left) / 2 + finalRect->left; finalCentre->y = (finalRect->bottom - finalRect->top) / 2 + finalRect->top; } HTHUMBNAIL RegisterLiveThumbnail( _In_ HWND dest, _In_ HWND src, _In_ RECT rect ); inline double linear( _In_ double percent, _In_ double start, _In_ double end, _In_ double total ) { return start + (end - start) * percent; } // p = t / d inline double easeOutQuad( _In_ double p ) { double m = p - 1; return 1 - m * m; }; DWORD WINAPI animate( _Inout_ LPVOID lpParam ); inline void InitializeAnimation( _Inout_ MonitorInfo* monitorInfo ) { monitorInfo->animation.delay_ms = 1000.0 / FPS; } inline void AddAnimation( _Inout_ AnimationInfo &animations, _In_ POINT initialCentre, _In_ POINT finalCentre, _In_ RECT initialRect, _In_ RECT finalRect, _In_ double scale, _In_ HWND hWnd, _In_ HTHUMBNAIL thumbnail ) { Animation animation; animation.start = initialCentre; animation.end = finalCentre; animation.w = (initialRect.right - initialRect.left); animation.h = (initialRect.bottom - initialRect.top); animation.scale = scale; animation.hWnd = hWnd; animation.thumb = thumbnail; animations.animations.push_back(animation); } BOOL BeginAnimateUpdate( _In_ MonitorInfo* info ); void EndAnimateUpdate( _In_ MonitorInfo* info ); BOOL DoAnimate( _In_ BOOL alreadyAcquired, _In_ UINT type, _In_ MonitorInfo* info, _In_ BOOL isOpening ); bool SortHwndByZorder( _In_ HWND hWnd1, _In_ HWND hWnd2 ); bool SortAnimationsByHwndZorder( _In_ Animation a1, _In_ Animation a2 ); RECT GetSearchRect( _In_ MonitorInfo* info ); void ShowSearch( _In_ MonitorInfo* info, _In_ WPARAM wParam );
6,559
C++
.h
256
22.554688
92
0.717887
valinet/WinOverview
39
6
2
GPL-2.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,510
constants.h
valinet_WinOverview/WinOverviewLibrary/constants.h
#pragma once #define BUFSIZE 4096 #define _columnSpacing 20; #define _rowSpacing 20; #define WINDOW_CLONE_MAXIMUM_SCALE 1.0 #define LAYOUT_SCALE_WEIGHT 1.0 #define LAYOUT_SPACE_WEIGHT 0.1 #define ANIMATION_DURATION_MS 150 #define FADE_DURATION_MS 120 #define FPS 120 #define AREA_BORDER 30 #define WM_THREAD_DONE (WM_USER + 0x0001) #define WM_ASK_MOUSE (WM_USER + 0x0002) #define WM_SHOW_SEARCH (WM_USER + 0x0003) #define WM_IS_SEARCH (WM_USER + 0x0004) #define CLASS_NAME L"ActivitiesOverviewWindowClassFull" #define CLASS_NAME_SIMPLE L"ActivitiesOverviewWindowClassSimple" #define CLASS_NAME_BKG L"ActivitiesOverviewWindowClassBkg"
666
C++
.h
18
34.222222
65
0.790221
valinet/WinOverview
39
6
2
GPL-2.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,512
NtUserBuildHwndList.h
valinet_WinOverview/WinOverview/NtUserBuildHwndList.h
#pragma once #include <Windows.h> #define STATUS_BUFFER_TOO_SMALL 0xC0000023 typedef NTSTATUS(WINAPI* NtUserBuildHwndList) ( HDESK in_hDesk, HWND in_hWndNext, BOOL in_EnumChildren, BOOL in_RemoveImmersive, DWORD in_ThreadID, UINT in_Max, HWND* out_List, UINT* out_Cnt ); // many thanks to: https://stackoverflow.com/questions/38205375/enumwindows-function-in-win10-enumerates-only-desktop-apps HWND* _Gui_BuildWindowList ( NtUserBuildHwndList pNtUserBuildHwndList, HDESK in_hDesk, HWND in_hWnd, BOOL in_EnumChildren, BOOL in_RemoveImmersive, UINT in_ThreadID, INT* out_Cnt ) { /* locals */ UINT lv_Max; UINT lv_Cnt; UINT lv_NtStatus; HWND* lv_List; // initial size of list lv_Max = 512; // retry to get list for (;;) { // allocate list if ((lv_List = (HWND*)malloc(lv_Max * sizeof(HWND))) == NULL) break; // call the api lv_NtStatus = pNtUserBuildHwndList( in_hDesk, in_hWnd, in_EnumChildren, in_RemoveImmersive, in_ThreadID, lv_Max, lv_List, &lv_Cnt); // success? if (lv_NtStatus == NOERROR) break; // free allocated list free(lv_List); // clear lv_List = NULL; // other error then buffersize? or no increase in size? if (lv_NtStatus != STATUS_BUFFER_TOO_SMALL || lv_Cnt <= lv_Max) break; // update max plus some extra to take changes in number of windows into account lv_Max = lv_Cnt + 16; } // return the count *out_Cnt = lv_Cnt; // return the list, or NULL when failed return lv_List; } /********************************************************/ /* enumerate all top level windows including metro apps */ /********************************************************/ BOOL Gui_RealEnumWindows( NtUserBuildHwndList pNtUserBuildHwndList, WNDENUMPROC in_Proc, LPARAM in_Param ) { /* locals */ INT lv_Cnt; HWND lv_hWnd; BOOL lv_Result; HWND lv_hFirstWnd; HWND lv_hDeskWnd; HWND* lv_List; // no error yet lv_Result = TRUE; // first try api to get full window list including immersive/metro apps lv_List = _Gui_BuildWindowList(pNtUserBuildHwndList, 0, 0, 0, 0, 0, &lv_Cnt); // success? if (lv_List) { // loop through list while (lv_Cnt-- > 0 && lv_Result) { // get handle lv_hWnd = lv_List[lv_Cnt]; // filter out the invalid entry (0x00000001) then call the callback if (IsWindow(lv_hWnd)) lv_Result = in_Proc(lv_hWnd, in_Param); } // free the list free(lv_List); } else { // get desktop window, this is equivalent to specifying NULL as hwndParent lv_hDeskWnd = GetDesktopWindow(); // fallback to using FindWindowEx, get first top-level window lv_hFirstWnd = FindWindowEx(lv_hDeskWnd, 0, 0, 0); // init the enumeration lv_Cnt = 0; lv_hWnd = lv_hFirstWnd; // loop through windows found // - since 2012 the EnumWindows API in windows has a problem (on purpose by MS) // that it does not return all windows (no metro apps, no start menu etc) // - luckally the FindWindowEx() still is clean and working while (lv_hWnd && lv_Result) { // call the callback lv_Result = in_Proc(lv_hWnd, in_Param); // get next window lv_hWnd = FindWindowEx(lv_hDeskWnd, lv_hWnd, 0, 0); // protect against changes in window hierachy during enumeration if (lv_hWnd == lv_hFirstWnd || lv_Cnt++ > 10000) break; } } // return the result return lv_Result; }
3,496
C++
.h
124
24.330645
123
0.655214
valinet/WinOverview
39
6
2
GPL-2.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,514
Gui.cpp
g1n0st_AyaGui/src/Gui/Gui.cpp
#include <Gui/Gui.h> #include <cmath> #include <cassert> #include <exception> #include <functional> #include <iostream> #include <algorithm> namespace Aya { PFNGLCREATESHADERPROC glCreateShader; PFNGLCREATEPROGRAMPROC glCreateProgram; PFNGLDELETESHADERPROC glDeleteShader; PFNGLDELETEPROGRAMPROC glDeleteProgram; PFNGLATTACHSHADERPROC glAttachShader; PFNGLDETACHSHADERPROC glDetachShader; PFNGLSHADERSOURCEPROC glShaderSource; PFNGLCOMPILESHADERPROC glCompileShader; PFNGLLINKPROGRAMPROC glLinkProgram; PFNGLVALIDATEPROGRAMPROC glValidateProgram; PFNGLUSEPROGRAMPROC glUseProgram; PFNGLGETSHADERINFOLOGPROC glGetShaderInfoLog; PFNGLGETPROGRAMINFOLOGPROC glGetProgramInfoLog; PFNGLGETSHADERIVPROC glGetShaderiv; PFNGLGETPROGRAMIVPROC glGetProgramiv; PFNGLUNIFORM1FPROC glUniform1f; PFNGLUNIFORM1FVPROC glUniform1fv; PFNGLUNIFORM2FPROC glUniform2f; PFNGLUNIFORM2FVPROC glUniform2fv; PFNGLUNIFORM3FPROC glUniform3f; PFNGLUNIFORM4FPROC glUniform4f; PFNGLUNIFORM1IPROC glUniform1i; PFNGLUNIFORM1IVPROC glUniform1iv; PFNGLUNIFORM2IPROC glUniform2i; PFNGLUNIFORM3IPROC glUniform3i; PFNGLUNIFORM4IPROC glUniform4i; PFNGLUNIFORMMATRIX3FVPROC glUniformMatrix3fv; PFNGLUNIFORMMATRIX4FVPROC glUniformMatrix4fv; PFNGLGETUNIFORMLOCATIONPROC glGetUniformLocation; PFNGLBINDFRAGDATALOCATIONEXTPROC glBindFragDataLocation; PFNGLISRENDERBUFFEREXTPROC glIsRenderbuffer; PFNGLBINDRENDERBUFFEREXTPROC glBindRenderbuffer; PFNGLDELETERENDERBUFFERSEXTPROC glDeleteRenderbuffers; PFNGLGENRENDERBUFFERSEXTPROC glGenRenderbuffers; PFNGLRENDERBUFFERSTORAGEEXTPROC glRenderbufferStorage; PFNGLRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC glRenderbufferStorageMultisample; PFNGLGETRENDERBUFFERPARAMETERIVEXTPROC glGetRenderbufferParameteriv; PFNGLISFRAMEBUFFEREXTPROC glIsFramebuffer; PFNGLBINDFRAMEBUFFEREXTPROC glBindFramebuffer; PFNGLDELETEFRAMEBUFFERSEXTPROC glDeleteFramebuffers; PFNGLGENFRAMEBUFFERSEXTPROC glGenFramebuffers; PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC glCheckFramebufferStatus; PFNGLFRAMEBUFFERTEXTURE1DEXTPROC glFramebufferTexture1D; PFNGLFRAMEBUFFERTEXTURE2DEXTPROC glFramebufferTexture2D; PFNGLFRAMEBUFFERTEXTURE3DEXTPROC glFramebufferTexture3D; PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC glFramebufferRenderbuffer; PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVEXTPROC glGetFramebufferAttachmentParameteriv; PFNGLBLITFRAMEBUFFEREXTPROC glBlitFramebuffer; PFNGLGENERATEMIPMAPEXTPROC glGenerateMipmap; PFNGLDRAWBUFFERSPROC glDrawBuffers; PFNGLDRAWRANGEELEMENTSPROC glDrawRangeElements; PFNGLACTIVETEXTUREPROC glActiveTexture; PFNGLCLIENTACTIVETEXTUREPROC glClientActiveTexture; PFNGLMULTITEXCOORD1FPROC glMultiTexcoord1f; PFNGLMULTITEXCOORD2FPROC glMultiTexcoord2f; PFNGLMULTITEXCOORD3FPROC glMultiTexcoord3f; PFNGLMULTITEXCOORD4FPROC glMultiTexcoord4f; PFNGLLOADTRANSPOSEMATRIXFPROC glLoadTransposeMatrixf; PFNGLBINDBUFFERPROC glBindBuffer; PFNGLBUFFERDATAPROC glBufferData; PFNGLBUFFERSUBDATAPROC glBufferSubData; PFNGLDELETEBUFFERSPROC glDeleteBuffers; PFNGLGENBUFFERSPROC glGenBuffers; PFNGLMAPBUFFERPROC glMapBuffer; PFNGLUNMAPBUFFERPROC glUnmapBuffer; PFNGLBLENDEQUATIONPROC glBlendEquation; PFNGLBLENDCOLORPROC glBlendColor; PFNGLBLENDFUNCSEPARATEPROC glBlendFuncSeperate; PFNGLBLENDEQUATIONSEPARATEPROC glBlendEquationSeperate; void InitializeOpenGLExtensions() { glCreateShader = (PFNGLCREATESHADEROBJECTARBPROC)wglGetProcAddress("glCreateShaderObjectARB"); glCreateProgram = (PFNGLCREATEPROGRAMOBJECTARBPROC)wglGetProcAddress("glCreateProgramObjectARB"); glAttachShader = (PFNGLATTACHSHADERPROC)wglGetProcAddress("glAttachShader"); glDetachShader = (PFNGLDETACHSHADERPROC)wglGetProcAddress("glDetachShader"); glDeleteShader = (PFNGLDELETESHADERPROC)wglGetProcAddress("glDeleteShader"); glDeleteProgram = (PFNGLDELETEPROGRAMPROC)wglGetProcAddress("glDeleteProgram"); glShaderSource = (PFNGLSHADERSOURCEPROC)wglGetProcAddress("glShaderSource"); glCompileShader = (PFNGLCOMPILESHADERPROC)wglGetProcAddress("glCompileShader"); glLinkProgram = (PFNGLLINKPROGRAMPROC)wglGetProcAddress("glLinkProgram"); glValidateProgram = (PFNGLVALIDATEPROGRAMPROC)wglGetProcAddress("glValidateProgram"); glUseProgram = (PFNGLUSEPROGRAMPROC)wglGetProcAddress("glUseProgram"); glGetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC)wglGetProcAddress("glGetShaderInfoLog"); glGetProgramInfoLog = (PFNGLGETPROGRAMINFOLOGPROC)wglGetProcAddress("glGetProgramInfoLog"); glGetShaderiv = (PFNGLGETSHADERIVPROC)wglGetProcAddress("glGetShaderiv"); glGetProgramiv = (PFNGLGETPROGRAMIVPROC)wglGetProcAddress("glGetProgramiv"); glUniform1f = (PFNGLUNIFORM1FPROC)wglGetProcAddress("glUniform1f"); glUniform1fv = (PFNGLUNIFORM1FVPROC)wglGetProcAddress("glUniform1fv"); glUniform2f = (PFNGLUNIFORM2FPROC)wglGetProcAddress("glUniform2f"); glUniform2fv = (PFNGLUNIFORM2FVPROC)wglGetProcAddress("glUniform2fv"); glUniform3f = (PFNGLUNIFORM3FPROC)wglGetProcAddress("glUniform3f"); glUniform4f = (PFNGLUNIFORM4FPROC)wglGetProcAddress("glUniform4f"); glUniform1i = (PFNGLUNIFORM1IPROC)wglGetProcAddress("glUniform1i"); glUniform1iv = (PFNGLUNIFORM1IVPROC)wglGetProcAddress("glUniform1iv"); glUniform2i = (PFNGLUNIFORM2IPROC)wglGetProcAddress("glUniform2i"); glUniform3i = (PFNGLUNIFORM3IPROC)wglGetProcAddress("glUniform3i"); glUniform4i = (PFNGLUNIFORM4IPROC)wglGetProcAddress("glUniform4i"); glUniformMatrix3fv = (PFNGLUNIFORMMATRIX3FVPROC)wglGetProcAddress("glUniformMatrix3fv"); glUniformMatrix4fv = (PFNGLUNIFORMMATRIX4FVPROC)wglGetProcAddress("glUniformMatrix4fv"); glGetUniformLocation = (PFNGLGETUNIFORMLOCATIONPROC)wglGetProcAddress("glGetUniformLocation"); glBindFragDataLocation = (PFNGLBINDFRAGDATALOCATIONEXTPROC)wglGetProcAddress("glBindFragDataLocationEXT"); glIsRenderbuffer = (PFNGLISRENDERBUFFEREXTPROC)wglGetProcAddress("glIsRenderbuffer"); glBindRenderbuffer = (PFNGLBINDRENDERBUFFEREXTPROC)wglGetProcAddress("glBindRenderbuffer"); glDeleteRenderbuffers = (PFNGLDELETERENDERBUFFERSEXTPROC)wglGetProcAddress("glDeleteRenderbuffers"); glGenRenderbuffers = (PFNGLGENRENDERBUFFERSEXTPROC)wglGetProcAddress("glGenRenderbuffers"); glRenderbufferStorage = (PFNGLRENDERBUFFERSTORAGEEXTPROC)wglGetProcAddress("glRenderbufferStorage"); glGetRenderbufferParameteriv = (PFNGLGETRENDERBUFFERPARAMETERIVEXTPROC)wglGetProcAddress("glGetRenderbufferParameteriv"); glIsFramebuffer = (PFNGLISFRAMEBUFFEREXTPROC)wglGetProcAddress("glIsFramebuffer"); glBindFramebuffer = (PFNGLBINDFRAMEBUFFEREXTPROC)wglGetProcAddress("glBindFramebuffer"); glDeleteFramebuffers = (PFNGLDELETEFRAMEBUFFERSEXTPROC)wglGetProcAddress("glDeleteFramebuffers"); glGenFramebuffers = (PFNGLGENFRAMEBUFFERSEXTPROC)wglGetProcAddress("glGenFramebuffers"); glCheckFramebufferStatus = (PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC)wglGetProcAddress("glCheckFramebufferStatus"); glFramebufferTexture1D = (PFNGLFRAMEBUFFERTEXTURE1DEXTPROC)wglGetProcAddress("glFramebufferTexture1D"); glFramebufferTexture2D = (PFNGLFRAMEBUFFERTEXTURE2DEXTPROC)wglGetProcAddress("glFramebufferTexture2D"); glFramebufferTexture3D = (PFNGLFRAMEBUFFERTEXTURE3DEXTPROC)wglGetProcAddress("glFramebufferTexture3D"); glFramebufferRenderbuffer = (PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC)wglGetProcAddress("glFramebufferRenderbuffer"); glGetFramebufferAttachmentParameteriv = (PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVEXTPROC)wglGetProcAddress("glGetFramebufferAttachmentParameteriv"); glBlitFramebuffer = (PFNGLBLITFRAMEBUFFEREXTPROC)wglGetProcAddress("glBlitFramebuffer"); glRenderbufferStorageMultisample = (PFNGLRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC)wglGetProcAddress("glRenderbufferStorageMultisample"); glGenerateMipmap = (PFNGLGENERATEMIPMAPEXTPROC)wglGetProcAddress("glGenerateMipmap"); glDrawBuffers = (PFNGLDRAWBUFFERSPROC)wglGetProcAddress("glDrawBuffers"); glDrawRangeElements = (PFNGLDRAWRANGEELEMENTSPROC)wglGetProcAddress("glDrawRangeElements"); glActiveTexture = (PFNGLACTIVETEXTUREPROC)wglGetProcAddress("glActiveTexture"); glClientActiveTexture = (PFNGLCLIENTACTIVETEXTUREPROC)wglGetProcAddress("glClientActiveTexture"); glMultiTexcoord1f = (PFNGLMULTITEXCOORD1FPROC)wglGetProcAddress("glMultiTexCoord1f"); glMultiTexcoord2f = (PFNGLMULTITEXCOORD2FPROC)wglGetProcAddress("glMultiTexCoord2f"); glMultiTexcoord3f = (PFNGLMULTITEXCOORD3FPROC)wglGetProcAddress("glMultiTexCoord3f"); glMultiTexcoord4f = (PFNGLMULTITEXCOORD4FPROC)wglGetProcAddress("glMultiTexCoord4f"); glLoadTransposeMatrixf = (PFNGLLOADTRANSPOSEMATRIXFPROC)wglGetProcAddress("glLoadTransposeMatrixf"); glBindBuffer = (PFNGLBINDBUFFERPROC)wglGetProcAddress("glBindBuffer"); glBufferData = (PFNGLBUFFERDATAPROC)wglGetProcAddress("glBufferData"); glDeleteBuffers = (PFNGLDELETEBUFFERSPROC)wglGetProcAddress("glDeleteBuffers"); glGenBuffers = (PFNGLGENBUFFERSPROC)wglGetProcAddress("glGenBuffers"); glBlendEquation = (PFNGLBLENDEQUATIONPROC)wglGetProcAddress("glBlendEquation"); glBlendColor = (PFNGLBLENDCOLORPROC)wglGetProcAddress("glBlendColor"); glBlendFuncSeperate = (PFNGLBLENDFUNCSEPARATEPROC)wglGetProcAddress("glBlendFuncSeperate"); glBlendEquationSeperate = (PFNGLBLENDEQUATIONSEPARATEPROC)wglGetProcAddress("glBlendEquationSeperate"); } GuiRenderer* GuiRenderer::mp_instance = nullptr; const GLfloat GuiRenderer::DEPTH_FAR = 0.8f; const GLfloat GuiRenderer::DEPTH_MID = 0.6f; const GLfloat GuiRenderer::DEPTH_NEAR = 0.4f; const GLchar* GuiRenderer::s_vertShaderSource = R"( varying vec2 texCoord; void main() { gl_Position = gl_Vertex; texCoord = gl_MultiTexCoord0.xy; })"; const GLchar* GuiRenderer::s_blurFragShaderSource = R"( uniform sampler2D texSampler; uniform float weights[13]; uniform vec2 offsets[13]; varying vec2 texCoord; void main() { vec4 sample = 0.0f; for(int i = 0; i < 13; i++) { sample += weights[i] * texture2DLod(texSampler, texCoord + offsets[i], 2); } gl_FragColor = vec4(sample.rgb, 1.0); })"; GuiRenderer::GuiRenderer() { m_handleProgram = glCreateProgram(); // Background Tex glGenTextures(1, &m_handleBackgroundTex); glBindTexture(GL_TEXTURE_2D, m_handleBackgroundTex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 16); glGenFramebuffers(1, &m_handleFBO); glGenRenderbuffers(1, &m_handleColorRBO); m_textListBase = glGenLists(128); HFONT font = CreateFont(16, 0, 0, 0, FW_BOLD, FALSE, FALSE, FALSE, DEFAULT_CHARSET, OUT_TT_PRECIS, CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY, FF_DECORATIVE | DEFAULT_PITCH, "Helvetica"); m_HDC = wglGetCurrentDC(); HFONT old_font = (HFONT)SelectObject(m_HDC, font); wglUseFontBitmaps(m_HDC, 0, 128, m_textListBase); //SelectObject(m_HDC, old_font); DeleteObject(font); // Compile and Load Shaders auto LoadShader = [](GLint type, const GLchar *source) { GLint handle = glCreateShader(type); GLint length = (GLint)strlen(source); glShaderSource(handle, 1, &source, &length); glCompileShader(handle); GLint compile_status; glGetShaderiv(handle, GL_COMPILE_STATUS, &compile_status); if (compile_status != GL_TRUE) throw std::runtime_error("GLSL compiled error"); return handle; }; GLint handle_vertex_shader = LoadShader(GL_VERTEX_SHADER, s_vertShaderSource); GLint handle_blur_frag_shader = LoadShader(GL_FRAGMENT_SHADER, s_blurFragShaderSource); glAttachShader(m_handleProgram, handle_vertex_shader); glAttachShader(m_handleProgram, handle_blur_frag_shader); auto ExcuteAndCheck = [](std::function<void(GLint)> glFunc, GLint handle) { GLint status; GLchar* status_buffer; GLint length; glFunc(handle); glGetProgramiv(handle, GL_INFO_LOG_LENGTH, &length); status_buffer = new GLchar[length]; glGetProgramInfoLog(handle, length, &length, status_buffer); glGetProgramiv(handle, GL_LINK_STATUS, &status); if (status != GL_TRUE) throw std::runtime_error(status_buffer); delete[] status_buffer; }; ExcuteAndCheck(glLinkProgram, m_handleProgram); ExcuteAndCheck(glValidateProgram, m_handleProgram); // Calculate circle coordinates const GLfloat phi_itvl = 6.2831853071796f / (CIRCLE_VERTEX_COUNT - 1); GLfloat phi = 0.0f; for (size_t i = 0; i < CIRCLE_VERTEX_COUNT - 1; ++i) { m_circleCoords[i * 2 + 0] = std::sinf(phi); m_circleCoords[i * 2 + 1] = -std::cosf(phi); phi += phi_itvl; } m_circleCoords[2 * CIRCLE_VERTEX_COUNT - 2] = m_circleCoords[0]; m_circleCoords[2 * CIRCLE_VERTEX_COUNT - 1] = m_circleCoords[1]; } GuiRenderer::~GuiRenderer() { glDeleteProgram(m_handleProgram); glDeleteTextures(1, &m_handleBackgroundTex); glDeleteFramebuffers(1, &m_handleFBO); glDeleteRenderbuffers(1, &m_handleColorRBO); } void GuiRenderer::resize(int width, int height) { m_width = width; m_height = height; // Init background texture glBindRenderbuffer(GL_RENDERBUFFER, m_handleColorRBO); glRenderbufferStorageMultisample(GL_RENDERBUFFER, 0, GL_RGBA, (width + 0x7) >> 2, (height + 0x7) >> 2); glBindRenderbuffer(GL_RENDERBUFFER, 0); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_handleFBO); glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, m_handleColorRBO); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); CalcGaussianBlurWeightsAndOffsets(); } void GuiRenderer::blurBackgroundTexture(int x0, int y0, int x1, int y1) { glBindTexture(GL_TEXTURE_2D, m_handleBackgroundTex); glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 0, 0, m_width, m_height, 0); glGenerateMipmap(GL_TEXTURE_2D); GLfloat u0 = (GLfloat)x0 / (GLfloat)m_width; GLfloat v0 = (GLfloat)y0 / (GLfloat)m_height; GLfloat u1 = (GLfloat)x1 / (GLfloat)m_width; GLfloat v1 = (GLfloat)y1 / (GLfloat)m_height; GLfloat rx0 = u0 * 2.f - 1.f; GLfloat ry0 = v0 * 2.f - 1.f; GLfloat rx1 = u1 * 2.f - 1.f; GLfloat ry1 = v1 * 2.f - 1.f; glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_handleFBO); glViewport(0, 0, (m_width + 0x7) >> 2, (m_height + 0x7) >> 2); glClear(GL_COLOR_BUFFER_BIT); glUseProgram(m_handleProgram); glUniform1i(glGetUniformLocation(m_handleProgram, "texSampler"), 0); glUniform1fv(glGetUniformLocation(m_handleProgram, "weights"), 13, m_gaussianWeights); glUniform2fv(glGetUniformLocation(m_handleProgram, "offsets"), 13, m_gaussianOffsets); glBindTexture(GL_TEXTURE_2D, m_handleBackgroundTex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glBegin(GL_QUADS); glTexCoord2f(u0, v0); glVertex3f(rx0, ry0, DEPTH_FAR); glTexCoord2f(u1, v0); glVertex3f(rx1, ry0, DEPTH_FAR); glTexCoord2f(u1, v1); glVertex3f(rx1, ry1, DEPTH_FAR); glTexCoord2f(u0, v1); glVertex3f(rx0, ry1, DEPTH_FAR); glEnd(); glUseProgram(0); glBindTexture(GL_TEXTURE_2D, 0); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); glViewport(0, 0, m_width, m_height); } void GuiRenderer::drawBackgroundTexture(int x0, int y0, int x1, int y1) { glBindFramebuffer(GL_READ_FRAMEBUFFER, m_handleFBO); glBlitFramebuffer((x0 + 0x7) >> 2, (y0 - 0x7) >> 2, (x1 - 0x7) >> 2, (y1 + 0x7) >> 2, x0, y0, x1, y1, GL_COLOR_BUFFER_BIT, GL_LINEAR); glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); } void GuiRenderer::drawLine(int x0, int y0, int x1, int y1, float depth) const { glBegin(GL_LINES); glVertex3f((GLfloat)x0, (GLfloat)y0, depth); glVertex3f((GLfloat)x1, (GLfloat)y1, depth); glEnd(); } void GuiRenderer::drawRect(int x0, int y0, int x1, int y1, float depth, const bool filled, const Color4f &color, const Color4f &blend_color) const { auto draw = [](int x0, int y0, int x1, int y1, float depth) { glBegin(GL_QUADS); glVertex3f((GLfloat)x0, (GLfloat)y0, depth); glVertex3f((GLfloat)x1, (GLfloat)y0, depth); glVertex3f((GLfloat)x1, (GLfloat)y1, depth); glVertex3f((GLfloat)x0, (GLfloat)y1, depth); glEnd(); }; glBlendColor(blend_color.r, blend_color.g, blend_color.b, blend_color.a); glColor4fv((GLfloat*)&color); if (filled) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); draw(x0 - 1, y0, x1, y1 + 1, depth); } else { glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); draw(x0, y0, x1, y1, depth); } } void GuiRenderer::drawRoundedRect(int x0, int y0, int x1, int y1, float depth, float radius, const bool filled, const Color4f &color, const Color4f &blend_color) const { glBlendColor(blend_color.r, blend_color.g, blend_color.b, blend_color.a); glColor4fv((GLfloat*)&color); if (filled) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glBegin(GL_TRIANGLE_FAN); // Center vertex glVertex3f((x0 + x1) * 0.5f, (y0 + y1) * 0.5f, depth); } else { radius += 1; glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glBegin(GL_LINE_STRIP); } const size_t quater_vertex_count = CIRCLE_VERTEX_COUNT / 4; glVertex3f((GLfloat)x0 + radius, (GLfloat)y0, depth); glVertex3f((GLfloat)x1 - radius, (GLfloat)y0, depth); for (size_t i = 0; i < quater_vertex_count; i++) { GLfloat x = x1 - radius + m_circleCoords[i * 2 + 0] * radius; GLfloat y = y0 + radius + m_circleCoords[i * 2 + 1] * radius; glVertex3f(x, y, depth); } glVertex3f((GLfloat)x1, (GLfloat)y0 + radius, depth); glVertex3f((GLfloat)x1, (GLfloat)y1 - radius, depth); for (size_t i = quater_vertex_count; i < 2 * quater_vertex_count; i++) { GLfloat x = x1 - radius + m_circleCoords[i * 2 + 0] * radius; GLfloat y = y1 - radius + m_circleCoords[i * 2 + 1] * radius; glVertex3f(x, y, depth); } glVertex3f((GLfloat)x1 - radius, (GLfloat)y1, depth); glVertex3f((GLfloat)x0 + radius, (GLfloat)y1, depth); for (size_t i = 2 * quater_vertex_count; i < 3 * quater_vertex_count; i++) { GLfloat x = x0 + radius + m_circleCoords[i * 2 + 0] * radius; GLfloat y = y1 - radius + m_circleCoords[i * 2 + 1] * radius; glVertex3f(x, y, depth); } glVertex3f((GLfloat)x0, (GLfloat)y1 - radius, depth); glVertex3f((GLfloat)x0, (GLfloat)y0 + radius, depth); for (size_t i = 3 * quater_vertex_count; i < 4 * quater_vertex_count; i++) { GLfloat x = x0 + radius + m_circleCoords[i * 2 + 0] * radius; GLfloat y = y0 + radius + m_circleCoords[i * 2 + 1] * radius; glVertex3f(x, y, depth); } glEnd(); } void GuiRenderer::drawHalfRoundedRect(int x0, int y0, int x1, int y1, float depth, float radius, const bool filled, const Color4f &color, const Color4f &blend_color) const { glBlendColor(blend_color.r, blend_color.g, blend_color.b, blend_color.a); glColor4fv((GLfloat*)&color); if (filled) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glBegin(GL_TRIANGLE_FAN); // Center vertex glVertex3f((x0 + x1) * 0.5f, (y0 + y1) * 0.5f, depth); } else { radius += 1; glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glBegin(GL_LINE_STRIP); } const size_t quater_vertex_count = CIRCLE_VERTEX_COUNT / 4; glVertex3f((GLfloat)x0 + radius, (GLfloat)y0, depth); glVertex3f((GLfloat)x1 - radius, (GLfloat)y0, depth); for (size_t i = 0; i < quater_vertex_count; i++) { GLfloat x = x1 - radius + m_circleCoords[i * 2 + 0] * radius; GLfloat y = y0 + radius + m_circleCoords[i * 2 + 1] * radius; glVertex3f(x, y, depth); } glVertex3f((GLfloat)x1, (GLfloat)y0 + radius, depth); glVertex3f((GLfloat)x1, (GLfloat)y1 - radius, depth); glVertex3f((GLfloat)x1, (GLfloat)y1, depth); glVertex3f((GLfloat)x1 - radius, (GLfloat)y1, depth); glVertex3f((GLfloat)x0 + radius, (GLfloat)y1, depth); glVertex3f((GLfloat)x0, (GLfloat)y1, depth); glVertex3f((GLfloat)x0, (GLfloat)y1 - radius, depth); glVertex3f((GLfloat)x0, (GLfloat)y0 + radius, depth); for (size_t i = 3 * quater_vertex_count; i < 4 * quater_vertex_count; i++) { GLfloat x = x0 + radius + m_circleCoords[i * 2 + 0] * radius; GLfloat y = y0 + radius + m_circleCoords[i * 2 + 1] * radius; glVertex3f(x, y, depth); } glEnd(); } void GuiRenderer::drawCircle(int x0, int y0, float depth, int radius, bool filled, const Color4f &color) const { glBlendColor(0.0f, 0.0f, 0.0f, 1.0f); glColor4fv((GLfloat*)&color); if (filled) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glBegin(GL_TRIANGLE_FAN); // Center vertex glVertex3f((GLfloat)x0, (GLfloat)y0, depth); } else { glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glBegin(GL_LINE_STRIP); } for (size_t i = 0; i < CIRCLE_VERTEX_COUNT; i++) { GLfloat x = x0 + m_circleCoords[i * 2 + 0] * radius; GLfloat y = y0 + m_circleCoords[i * 2 + 1] * radius; glVertex3f(x, y, depth); } glEnd(); } void GuiRenderer::drawString(int x0, int y0, float depth, const char *text, int length) const { glListBase(m_textListBase); glRasterPos3f((GLfloat)x0, (GLfloat)y0 + 10.f, depth); if (~length) { assert(length >= 0 && length <= (int)strlen(text)); glCallLists(length, GL_UNSIGNED_BYTE, text); } else { glCallLists((GLsizei)strlen(text), GL_UNSIGNED_BYTE, text); } } void GuiRenderer::CalcGaussianBlurWeightsAndOffsets() { auto GaussianDistribution = [](GLfloat x, GLfloat y, GLfloat rho) { const GLfloat pi = 3.141592653589793238462643383279f; float g = 1.f / std::sqrtf(2.f * pi * rho * rho); g *= std::expf(-(x * x + y * y) / (2.f * rho * rho)); return g; }; GLfloat tu = 4.f / (GLfloat)m_width; GLfloat tv = 4.f / (GLfloat)m_height; GLfloat total_weight = 0.f; size_t index = 0; for (auto x : {-2, -1, 0, 1, 2}) { for (auto y : { -2, -1, 0, 1, 2 }) { if (std::abs(x) + std::abs(y) > 2) continue; // Get the unscaled Gaussian intensity for this offset m_gaussianOffsets[index * 2 + 0] = x * tu; m_gaussianOffsets[index * 2 + 1] = y * tv; m_gaussianWeights[index] = GaussianDistribution(GLfloat(x), GLfloat(y), 1.f); total_weight += m_gaussianWeights[index]; ++index; } } for (size_t i = 0; i < index; i++) m_gaussianWeights[i] /= total_weight; } // Immediate Mode GUI Implementation GuiStates *AyaGui::states; void AyaGui::Init() { states = new GuiStates; states->activeId = -1; states->movingId = -1; states->activeDialogId = -1; states->keyState.key = 0; states->keyState.funckey = FunctionKey::None; states->keyState.keymode = KeyMode::None; states->editingId = -1; states->scrollerInitY = 0; } void AyaGui::Release() { delete states; states = nullptr; GuiRenderer::deleteInstance(); } void AyaGui::Resize(int width, int height) { states->screenWidth = width; states->screenHeight = height; GuiRenderer::instance()->resize(width, height); } void AyaGui::Vertical() { states->currentGrowthStrategy = GrowthStrategy::Vertical; } void AyaGui::Horizontal() { states->currentGrowthStrategy = GrowthStrategy::Horizontal; } void AyaGui::ExpandVertical(int margin) { states->currentPosY += margin; } void AyaGui::ExpandHorizontal(int margin) { states->currentPosX += margin; } void AyaGui::NextLine(int margin, int padding) { states->currentPosY += margin; states->currentPosX = padding; } void AyaGui::Target(int x, int y) { states->currentPosX = x; states->currentPosY = y; } void AyaGui::BeginFrame() { states->currentId = 0; states->currentDialogId = 0; states->hoveredId = -1; } void AyaGui::EndFrame() { states->globalMouseState.action = MouseAction::None; states->keyState.key = 0; states->keyState.funckey = FunctionKey::None; states->keyState.keymode = KeyMode::None; } void AyaGui::BeginDialog(LayoutStrategy layout, int &x, int &y, const char *title, const int width, const int height, GrowthStrategy growth_strategy) { auto dialog_id(states->currentDialogId++); assert(layout == LayoutStrategy::Fixed || layout == LayoutStrategy::Floating); states->currentLayoutStrategy = layout; states->currentGrowthStrategy = growth_strategy; states->dialogWidth = width; states->dialogHeight = height; states->dialogPosX = x; states->dialogPosY = y; states->currentPosX = c_paddingLeft; if (layout == LayoutStrategy::Floating || title) states->currentPosY = c_titledDialogPaddingTop; else states->currentPosY = c_untitledDialogPaddingTop; states->widgetEndX = states->dialogWidth - c_paddingLeft; states->mouseState = states->globalMouseState; states->mouseState.x = states->globalMouseState.x - states->dialogPosX; states->mouseState.y = states->globalMouseState.y - states->dialogPosY; int mouse_x = states->mouseState.x; int mouse_y = states->mouseState.y; // When dialog is moving, logical frame is prev frame if (states->movingId == dialog_id && layout == LayoutStrategy::Floating) { mouse_x -= states->globalMouseState.x - states->prevGlobalMouseState.x; mouse_y -= states->globalMouseState.y - states->prevGlobalMouseState.y; } if (PtInRect(mouse_x, mouse_y, 0, 0, states->dialogWidth, states->dialogHeight)) { if (states->mouseState.action == MouseAction::LButtonDown) { states->activeDialogId = dialog_id; if (layout == LayoutStrategy::Floating && PtInRect(mouse_x, mouse_y, 0, 0, states->dialogWidth, c_dialogTitleHeight)) { states->movingId = dialog_id; } } } if (states->mouseState.action == MouseAction::LButtonUp) { if (states->activeDialogId == dialog_id) states->activeDialogId = -1; if (layout == LayoutStrategy::Floating && states->movingId == dialog_id) states->movingId = -1; } if (layout == LayoutStrategy::Floating && states->movingId == dialog_id) { if (states->activeDialogId == dialog_id && PtInRect(mouse_x, mouse_y, 0, 0, states->dialogWidth, c_dialogTitleHeight)) { x += states->globalMouseState.x - states->prevGlobalMouseState.x; y += states->globalMouseState.y - states->prevGlobalMouseState.y; states->dialogPosX = x; states->dialogPosY = y; states->mouseState.x = states->globalMouseState.x - states->dialogPosX; states->mouseState.y = states->globalMouseState.y - states->dialogPosY; states->prevGlobalMouseState = states->globalMouseState; } else states->movingId = -1; } if (layout == LayoutStrategy::Fixed && states->movingId == dialog_id) { states->movingId = -1; } glClear(GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(0, states->screenWidth, 0, states->screenHeight, 1, -1); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); // Render the blurred background texture glPushAttrib(GL_ALL_ATTRIB_BITS); glEnable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); glDisable(GL_DEPTH_TEST); GuiRenderer::instance()->blurBackgroundTexture(states->dialogPosX, states->screenHeight - states->dialogPosY, states->dialogPosX + states->dialogWidth, states->screenHeight - (states->dialogPosY + states->dialogHeight)); GuiRenderer::instance()->drawBackgroundTexture(states->dialogPosX, states->screenHeight - states->dialogPosY, states->dialogPosX + states->dialogWidth, states->screenHeight - (states->dialogPosY + states->dialogHeight)); GuiRenderer::instance()->blurBackgroundTexture(states->dialogPosX, states->screenHeight - states->dialogPosY, states->dialogPosX + states->dialogWidth, states->screenHeight - (states->dialogPosY + states->dialogHeight)); GuiRenderer::instance()->drawBackgroundTexture(states->dialogPosX, states->screenHeight - states->dialogPosY, states->dialogPosX + states->dialogWidth, states->screenHeight - (states->dialogPosY + states->dialogHeight)); GuiRenderer::instance()->blurBackgroundTexture(states->dialogPosX, states->screenHeight - states->dialogPosY, states->dialogPosX + states->dialogWidth, states->screenHeight - (states->dialogPosY + states->dialogHeight)); GuiRenderer::instance()->drawBackgroundTexture(states->dialogPosX, states->screenHeight - states->dialogPosY, states->dialogPosX + states->dialogWidth, states->screenHeight - (states->dialogPosY + states->dialogHeight)); glTranslatef((GLfloat)states->dialogPosX, (GLfloat)states->screenHeight - states->dialogPosY, 0.0f); glScalef(1.0f, -1.0f, 1.0f); glLineWidth(1.0f); glDepthFunc(GL_LEQUAL); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_CONSTANT_ALPHA); glBlendEquation(GL_FUNC_ADD); GuiRenderer::instance()->drawRoundedRect(0, 0, states->dialogWidth, states->dialogHeight, GuiRenderer::DEPTH_FAR, 12.0f, true, { 0.1f, 0.1f, 0.1f, 1.f }, { 0.0f, 0.0f, 0.0f, 0.2f }); if (layout == LayoutStrategy::Floating) { GuiRenderer::instance()->drawHalfRoundedRect(0, 0, states->dialogWidth, c_dialogTitleHeight, GuiRenderer::DEPTH_FAR, 12.0f, true, { 0.1f, 0.1f, 0.1f, 1.0f }, { 0.0f, 0.0f, 0.0f, 0.03f }); } if (title) { glColor4f(1.0f, 1.0f, 1.0f, 1.0f); GuiRenderer::instance()->drawString(10, 6, GuiRenderer::DEPTH_FAR, title); } glEnable(GL_DEPTH_TEST); } void AyaGui::BeginSidebarDialog(LayoutStrategy layout, const int width, const int height, GrowthStrategy growth_strategy) { auto dialog_id(states->currentDialogId++); assert(layout == LayoutStrategy::DockLeft || layout == LayoutStrategy::DockRight); states->currentLayoutStrategy = layout; states->currentGrowthStrategy = growth_strategy; switch (layout) { case LayoutStrategy::DockRight: states->dialogWidth = c_sidebarWidth; states->dialogHeight = states->screenHeight; states->dialogPosX = states->screenWidth - states->dialogWidth; states->dialogPosY = 0; states->currentPosX = c_paddingLeft; states->currentPosY = c_sidebarPaddingTop; states->widgetEndX = states->dialogWidth - c_paddingLeft; break; case LayoutStrategy::DockLeft: states->dialogWidth = c_sidebarWidth; states->dialogHeight = states->screenHeight; states->dialogPosX = 0; states->dialogPosY = 0; states->currentPosX = c_paddingLeft; states->currentPosY = c_sidebarPaddingTop; states->widgetEndX = states->dialogWidth - c_paddingLeft; break; } states->mouseState = states->globalMouseState; states->mouseState.x = states->globalMouseState.x - states->dialogPosX; states->mouseState.y = states->globalMouseState.y - states->dialogPosY; if (states->mouseState.x >= 0 && states->mouseState.x < states->dialogWidth && states->mouseState.y > 0 && states->mouseState.y <= states->dialogHeight) { if (states->mouseState.action == MouseAction::LButtonDown) states->activeDialogId = dialog_id; } if (states->mouseState.action == MouseAction::LButtonUp) { if (states->activeDialogId == dialog_id) states->activeDialogId = -1; } glClear(GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(0, states->screenWidth, 0, states->screenHeight, 1, -1); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); // Render the blurred background texture glPushAttrib(GL_ALL_ATTRIB_BITS); glEnable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); glDisable(GL_DEPTH_TEST); GuiRenderer::instance()->blurBackgroundTexture(states->dialogPosX, states->screenHeight - states->dialogPosY, states->dialogPosX + states->dialogWidth, states->screenHeight - (states->dialogPosY + states->dialogHeight)); GuiRenderer::instance()->drawBackgroundTexture(states->dialogPosX, states->screenHeight - states->dialogPosY, states->dialogPosX + states->dialogWidth, states->screenHeight - (states->dialogPosY + states->dialogHeight)); GuiRenderer::instance()->blurBackgroundTexture(states->dialogPosX, states->screenHeight - states->dialogPosY, states->dialogPosX + states->dialogWidth, states->screenHeight - (states->dialogPosY + states->dialogHeight)); GuiRenderer::instance()->drawBackgroundTexture(states->dialogPosX, states->screenHeight - states->dialogPosY, states->dialogPosX + states->dialogWidth, states->screenHeight - (states->dialogPosY + states->dialogHeight)); GuiRenderer::instance()->blurBackgroundTexture(states->dialogPosX, states->screenHeight - states->dialogPosY, states->dialogPosX + states->dialogWidth, states->screenHeight - (states->dialogPosY + states->dialogHeight)); GuiRenderer::instance()->drawBackgroundTexture(states->dialogPosX, states->screenHeight - states->dialogPosY, states->dialogPosX + states->dialogWidth, states->screenHeight - (states->dialogPosY + states->dialogHeight)); glTranslatef((GLfloat)states->dialogPosX, (GLfloat)states->screenHeight - states->dialogPosY, 0.0f); glScalef(1.0f, -1.0f, 1.0f); glLineWidth(1.0f); glDepthFunc(GL_LEQUAL); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_CONSTANT_ALPHA); glBlendEquation(GL_FUNC_ADD); // Draw blurred background glBlendColor(1.0f, 1.0f, 1.0f, 0.5f); glColor4f(0.0f, 0.0f, 0.0f, 0.5f); glBegin(GL_QUADS); glVertex3f(0.0f, 0.0f, GuiRenderer::DEPTH_FAR); glVertex3f((GLfloat)states->dialogWidth, 0.0f, GuiRenderer::DEPTH_FAR); glVertex3f((GLfloat)states->dialogWidth, (GLfloat)states->dialogHeight, GuiRenderer::DEPTH_FAR); glVertex3f(0.0f, (GLfloat)states->dialogHeight, GuiRenderer::DEPTH_FAR); glEnd(); glEnable(GL_DEPTH_TEST); } void AyaGui::EndDialog() { glPopAttrib(); glPopMatrix(); glMatrixMode(GL_PROJECTION); glPopMatrix(); } bool AyaGui::HandleMouseEvent(const MouseEvent &mouse) { if (states->movingId == -1) states->prevGlobalMouseState = states->globalMouseState; states->globalMouseState = mouse; return states->activeDialogId != -1; } bool AyaGui::HandleKeyboardEvent(const KeyboardEvent &key) { states->keyState = key; return states->activeDialogId != -1; } void AyaGui::Text(const char *str, ...) { states->currentId++; va_list args; va_start(args, str); char buff[1024]; const int size = vsnprintf(buff, sizeof(buff) - 1, str, args); va_end(args); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); GuiRenderer::instance()->drawString(states->currentPosX, states->currentPosY + 3, GuiRenderer::DEPTH_MID, buff); if (states->currentGrowthStrategy == GrowthStrategy::Vertical) { states->currentPosY += c_textHeight + c_defaultMarginBottom; states->currentPosX = c_paddingLeft; } else { int line_length = 0; SIZE text_extent; for (int i = 0; i < size; i++) { GetTextExtentPoint32A(GuiRenderer::instance()->getHDC(), &buff[i], 1, &text_extent); line_length += text_extent.cx; } states->currentPosX += line_length + c_defaultMarginRight; } } void AyaGui::Text(Color4f color, const char *str, ...) { states->currentId++; va_list args; va_start(args, str); char buff[1024]; const int size = vsnprintf(buff, sizeof(buff) - 1, str, args); va_end(args); glColor4f(color.r, color.g, color.b, color.a); GuiRenderer::instance()->drawString(states->currentPosX, states->currentPosY + 3, GuiRenderer::DEPTH_MID, buff); if (states->currentGrowthStrategy == GrowthStrategy::Vertical) { states->currentPosY += c_textHeight + c_defaultMarginBottom; states->currentPosX = c_paddingLeft; } else { int line_length = 0; SIZE text_extent; for (int i = 0; i < size; i++) { GetTextExtentPoint32A(GuiRenderer::instance()->getHDC(), &buff[i], 1, &text_extent); line_length += text_extent.cx; } states->currentPosX += line_length + c_defaultMarginRight; } } void AyaGui::MultilineText(const char *str, ...) { states->currentId++; va_list args; va_start(args, str); char buff[4096]; const int size = vsnprintf(buff, sizeof(buff) - 1, str, args); va_end(args); std::vector<int> line_idx; std::string reformatted_str; line_idx.clear(); line_idx.push_back(0); // Split Text into lines int line_length = 0; for (int i = 0; i < size; i++) { if (buff[i] == '\n') { reformatted_str += '\0'; line_length = 0; line_idx.push_back(reformatted_str.length()); } else { reformatted_str += buff[i]; SIZE text_extent; GetTextExtentPoint32A(GuiRenderer::instance()->getHDC(), &buff[i], 1, &text_extent); line_length += text_extent.cx; if (line_length >= states->widgetEndX - states->currentPosX) { reformatted_str += '\0'; line_length = 0; line_idx.push_back(reformatted_str.length()); } } } // Render Text glColor4f(1.0f, 1.0f, 1.0f, 1.0f); for (size_t i = 0; i < line_idx.size(); i++) { GuiRenderer::instance()->drawString(states->currentPosX, states->currentPosY + i * c_multilineTextHeight, GuiRenderer::DEPTH_MID, reformatted_str.c_str() + line_idx[i]); } if (states->currentGrowthStrategy == GrowthStrategy::Vertical) { states->currentPosY += line_idx.size() * c_multilineTextHeight + c_defaultMarginBottom; states->currentPosX = c_paddingLeft; } else states->currentPosX += c_defaultMarginRight; } bool AyaGui::Button(const char *label, const int width, const int height, const bool banned) { bool triggered = false; const int id(states->currentId++); const int left = states->currentPosX; const int right = states->currentPosX + width > states->widgetEndX ? states->widgetEndX : states->currentPosX + width; const int top = states->currentPosY; const int bottom = states->currentPosY + height; if (!banned) { bool in_rect = PtInRect(states->mouseState.x, states->mouseState.y, left, top, right, bottom); if (in_rect) { if (states->mouseState.action == MouseAction::LButtonDown) states->activeId = id; states->hoveredId = id; } if (states->mouseState.action == MouseAction::LButtonUp) { if (states->activeId == id) { states->activeId = -1; if (in_rect) triggered = true; } } } else { if (states->activeId == id) states->activeId = -1; } float btn_radius = 5.0f; if (banned) { GuiRenderer::instance()->drawRoundedRect(left, top, right, bottom, GuiRenderer::DEPTH_MID, btn_radius, true, { 1.0f, 1.0f, 1.0f, 0.3f }); glColor4f(0.15f, 0.15f, 0.15f, 0.15f); } else if (states->hoveredId == id && states->activeId == id) { GuiRenderer::instance()->drawRoundedRect(left + 1, top + 1, right - 1, bottom - 1, GuiRenderer::DEPTH_MID, btn_radius, true, { 1.0f, 1.0f, 1.0f, 0.65f }); glColor4f(0.15f, 0.15f, 0.15f, 0.15f); } else if (states->hoveredId == id && states->activeId == -1 || states->activeId == id) { GuiRenderer::instance()->drawRoundedRect(left, top, right, bottom, GuiRenderer::DEPTH_MID, btn_radius, true, { 1.0f, 1.0f, 1.0f, 0.5f }); glColor4f(0.15f, 0.15f, 0.15f, 0.15f); } else { GuiRenderer::instance()->drawRoundedRect(left, top, right, bottom, GuiRenderer::DEPTH_MID, btn_radius, false, { 1.0f, 1.0f, 1.0f, 0.5f }); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); } SIZE text_extent; GetTextExtentPoint32A(GuiRenderer::instance()->getHDC(), label, strlen(label), &text_extent); glBlendColor(0.0f, 0.0f, 0.0f, 0.0f); GuiRenderer::instance()->drawString((right + left - text_extent.cx) / 2, (top + bottom - text_extent.cy) / 2 + 4, GuiRenderer::DEPTH_MID, label); if (states->currentGrowthStrategy == GrowthStrategy::Vertical) { states->currentPosY += height + c_defaultMarginBottom; states->currentPosX = c_paddingLeft; } else { states->currentPosX += right - left + c_defaultMarginRight; } return triggered; } void AyaGui::Line() { glLineWidth(1.0f); glColor4f(1.0f, 1.0f, 1.0f, 0.5f); if (states->currentGrowthStrategy == GrowthStrategy::Horizontal) { states->currentGrowthStrategy = GrowthStrategy::Vertical; states->currentPosY += c_defaultMarginBottom + c_lineMarginBottom; states->currentPosX = c_paddingLeft; } GuiRenderer::instance()->drawLine(5, states->currentPosY, states->dialogWidth - 5, states->currentPosY, GuiRenderer::DEPTH_MID); states->currentPosY += c_lineMarginBottom; } void AyaGui::ComboBox(const char *label, const std::vector<std::string> items, int &selected, int width, const bool banned) { if (label) Text(label); if (states->currentGrowthStrategy == GrowthStrategy::Vertical) states->currentPosY -= c_defaultMarginBottom / 2; else states->currentPosX -= c_defaultMarginRight / 2; const int id(states->currentId++); if (width + states->currentPosX > states->widgetEndX) width = states->widgetEndX - states->currentPosX; const int frame_left = states->currentPosX; const int frame_top = states->currentPosY; const int frame_right = states->currentPosX + width; const int frmae_bottom = states->currentPosY + c_comboBoxHeight; static bool list_down_current_frame; list_down_current_frame = false; if (!banned) { if (PtInRect(states->mouseState.x, states->mouseState.y, frame_left, frame_top, frame_right, frmae_bottom)) { if (states->mouseState.action == MouseAction::LButtonDown) { if (states->activeId != id) states->activeId = id; else if (states->activeId == id) states->activeId = -1; list_down_current_frame = true; } states->hoveredId = id; } } else { if (states->activeId == id) states->activeId = -1; } Color4f button_color = !banned ? (states->activeId == id || states->hoveredId == id && states->activeId == -1 ? Color4f(1.0f, 1.0f, 1.0f, 0.65f) : Color4f(1.0f, 1.0f, 1.0f, 0.5f)) : Color4f(1.0f, 1.0f, 1.0f, 0.3f); GuiRenderer::instance()->drawRect(frame_left, frame_top, frame_right, frmae_bottom, GuiRenderer::DEPTH_MID, false, button_color); GuiRenderer::instance()->drawRect(frame_right - c_comboBoxHeight, frame_top + 1, frame_right - 1, frmae_bottom - 1, GuiRenderer::DEPTH_MID, true, button_color); glBlendColor(0.0f, 0.0f, 0.0f, 0.0f); if (!banned) glColor4f(1.0f, 1.0f, 1.0f, 1.0f); else glColor4f(1.0f, 1.0f, 1.0f, 0.65f); if (selected >= 0 && selected < int(items.size())) GuiRenderer::instance()->drawString(frame_left + 3, frame_top + 5, GuiRenderer::DEPTH_MID, items[selected].c_str()); else GuiRenderer::instance()->drawString(frame_left + 5, frame_top + 5, GuiRenderer::DEPTH_MID, "..."); if (states->activeId == id) { const int drop_left = states->currentPosX; const int drop_top = states->currentPosY + c_comboBoxHeight; const int drop_right = drop_left + width - c_comboBoxHeight; const int drop_bottom = drop_top + 1 + int(items.size()) * c_comboBoxItemHeight; if (states->mouseState.action == MouseAction::LButtonDown) { if (PtInRect(states->mouseState.x, states->mouseState.y, drop_left, drop_top, drop_right, drop_bottom)) selected = (states->mouseState.y - drop_top) / c_comboBoxItemHeight; if (!list_down_current_frame) { states->activeId = -1; states->hoveredId = id; states->mouseState.action = MouseAction::None; } } GuiRenderer::instance()->drawRect(drop_left, drop_top + 1, drop_right, drop_bottom, GuiRenderer::DEPTH_NEAR, true, { 0.25f, 0.25f, 0.25f, 1.0f }); int hovered_idx = (states->mouseState.y - drop_top) / c_comboBoxItemHeight; if (hovered_idx < 0) hovered_idx = 0; if (hovered_idx >= int(items.size())) hovered_idx = int(items.size()) - 1; for (int i = 0; i < int(items.size()); i++) { if (i == hovered_idx) { GuiRenderer::instance()->drawRect( drop_left, drop_top + 2 + hovered_idx * c_comboBoxItemHeight, drop_right - 1, drop_top + 1 + (hovered_idx + 1) * c_comboBoxItemHeight, GuiRenderer::DEPTH_NEAR, true, { 0.4f, 0.4f, 0.4f, 0.5f }); glBlendColor(0.0f, 0.0f, 0.0f, 0.0f); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); } else { glBlendColor(0.0f, 0.0f, 0.0f, 0.0f); glColor4f(0.9f, 0.9f, 0.9f, 1.0f); } GuiRenderer::instance()->drawString(drop_left + 3, drop_top + 6 + i * c_comboBoxItemHeight, GuiRenderer::DEPTH_NEAR, items[i].c_str()); } } if (states->currentGrowthStrategy == GrowthStrategy::Vertical) { states->currentPosY += c_comboBoxHeight + c_defaultMarginBottom; states->currentPosX = c_paddingLeft; } else states->currentPosX += width + c_defaultMarginBottom; } bool AyaGui::CheckBox(const char *label, bool &checked, const bool banned) { bool triggered = false; const int id(states->currentId++); const int box_left = states->currentPosX; const int box_top = states->currentPosY; const int box_right = box_left + c_checkBoxSize; const int box_bottom = box_top + c_checkBoxSize; if (!banned) { if (PtInRect(states->mouseState.x, states->mouseState.y, box_left, box_top, box_right, box_bottom)) { if (states->mouseState.action == MouseAction::LButtonDown) states->activeId = id; if (states->mouseState.action == MouseAction::LButtonUp) { if (states->activeId == id) { states->activeId = -1; checked = !checked; triggered = true; } } states->hoveredId = id; } else { if (states->mouseState.action == MouseAction::Move) if (states->activeId == id) states->activeId = -1; } } else { if (states->activeId == id) states->activeId = -1; } const Color4f color1 = banned ? Color4f(1.0f, 1.0f, 1.0f, 0.3f) : states->hoveredId == id && states->activeId == -1 ? Color4f(1.0f, 1.0f, 1.0f, 0.65f) : Color4f(1.0f, 1.0f, 1.0f, 0.5f); GuiRenderer::instance()->drawRect(box_left, box_top, box_right, box_bottom, GuiRenderer::DEPTH_MID, false, color1); const Color4f color2 = checked ? color1 : states->hoveredId == id && states->activeId == -1 && !banned ? Color4f(1.0f, 1.0f, 1.0f, 0.15f) : Color4f(1.0f, 1.0f, 1.0f, 0.1f); GuiRenderer::instance()->drawRect(box_left + 2, box_top + 2, box_right - 2, box_bottom - 2, GuiRenderer::DEPTH_MID, true, color2); if (!banned) glColor4f(1.0f, 1.0f, 1.0f, 1.0f); else glColor4f(1.0f, 1.0f, 1.0f, 0.65f); GuiRenderer::instance()->drawString(box_right + 7, box_top + 2, GuiRenderer::DEPTH_MID, label); if (states->currentGrowthStrategy == GrowthStrategy::Vertical) { states->currentPosY += c_checkBoxSize + c_defaultMarginBottom; states->currentPosX = c_paddingLeft; } else { SIZE text_extent; GetTextExtentPoint32A(GuiRenderer::instance()->getHDC(), label, strlen(label), &text_extent); states->currentPosX += 7 + c_checkBoxSize + text_extent.cx + c_defaultMarginRight; } return triggered; } bool AyaGui::RadioButton(const char *label, int active, int &current, const bool banned) { bool triggered = false; const int id(states->currentId++); const int box_left = states->currentPosX; const int box_top = states->currentPosY; const int box_right = box_left + c_radioButtonCircleDiameter; const int box_bottom = box_top + c_radioButtonCircleDiameter; if (!banned) { if (PtInRect(states->mouseState.x, states->mouseState.y, box_left, box_top, box_right, box_bottom)) { if (states->mouseState.action == MouseAction::LButtonDown) states->activeId = id; if (states->mouseState.action == MouseAction::LButtonUp) { if (states->activeId == id) { states->activeId = -1; current = active; triggered = true; } } states->hoveredId = id; } else { if (states->mouseState.action == MouseAction::Move) if (states->activeId == id) states->activeId = -1; } } else { if (states->activeId == id) states->activeId = -1; } const Color4f color1 = banned ? Color4f(1.0f, 1.0f, 1.0f, 0.3f) : states->hoveredId == id && states->activeId == -1 ? Color4f(1.0f, 1.0f, 1.0f, 0.65f) : Color4f(1.0f, 1.0f, 1.0f, 0.5f); GuiRenderer::instance()->drawCircle((box_left + box_right) / 2, (box_top + box_bottom) / 2, GuiRenderer::DEPTH_MID, c_radioButtonCircleDiameter / 2, false, color1); const Color4f color2 = (current == active) ? color1 : states->hoveredId == id && states->activeId == -1 && !banned ? Color4f(1.0f, 1.0f, 1.0f, 0.15f) : Color4f(0.0f, 0.0f, 0.0f, 0.0f); GuiRenderer::instance()->drawCircle((box_left + box_right) / 2, (box_top + box_bottom) / 2, GuiRenderer::DEPTH_MID, c_radioButtonCircleDiameter / 2 - 2, true, color2); if (!banned) glColor4f(1.0f, 1.0f, 1.0f, 1.0f); else glColor4f(1.0f, 1.0f, 1.0f, 0.65f); GuiRenderer::instance()->drawString(box_right + 7, box_top + 2, GuiRenderer::DEPTH_MID, label); if (states->currentGrowthStrategy == GrowthStrategy::Vertical) { states->currentPosY += c_checkBoxSize + c_defaultMarginBottom; states->currentPosX = c_paddingLeft; } else { SIZE text_extent; GetTextExtentPoint32A(GuiRenderer::instance()->getHDC(), label, strlen(label), &text_extent); states->currentPosX += 7 + c_checkBoxSize + text_extent.cx + c_defaultMarginRight; } return triggered; } void AyaGui::ColorBlock(float r, float g, float b, int size) { const int block_left = states->currentPosX; const int block_top = states->currentPosY; const int block_right = block_left + size; const int block_bottom = block_top + size; GuiRenderer::instance()->drawRect(block_left - 1, block_top - 1, block_right + 1, block_bottom + 1, GuiRenderer::DEPTH_MID, false, { 1.0f, 1.0f, 1.0f, 1.0f }); GuiRenderer::instance()->drawRect(block_left, block_top, block_right, block_bottom, GuiRenderer::DEPTH_MID, true, { r, g, b, 1.0f }); auto To0x = [](float val) { static const char* table[0x10] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F" }; const uint32_t uint_val = uint32_t(val * 0xFF); return std::string(table[uint_val % 0x10]) + std::string(table[uint_val / 0x10]); }; if (PtInRect(states->mouseState.x, states->mouseState.y, block_left, block_top, block_right, block_bottom)) { std::string encode = "#" + To0x(r) + To0x(g) + To0x(b); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); GuiRenderer::instance()->drawString(states->mouseState.x + 15, states->mouseState.y + 15, GuiRenderer::DEPTH_NEAR, encode.c_str()); } } void AyaGui::InputText(std::string &str, int width, const bool auto_select_all, const bool auto_clear_on_enter, const bool banned) { const int id(states->currentId++); auto calc_prefix = [&]() { states->stringWidthPrefixSum.clear(); states->stringWidthPrefixSum.push_back(0); for (auto c : states->stringBuffer) { SIZE text_extent; GetTextExtentPoint32A(GuiRenderer::instance()->getHDC(), &c, 1, &text_extent); states->stringWidthPrefixSum.push_back(text_extent.cx + states->stringWidthPrefixSum.back()); } }; if (states->currentPosX + width > states->widgetEndX) width = states->widgetEndX - states->currentPosX; const int left = states->currentPosX; const int top = states->currentPosY; const int right = left + width; const int bottom = top + c_inputTextDefaultHeight; if (!banned) { if (PtInRect(states->mouseState.x, states->mouseState.y, left, top, right, bottom)) { if (states->mouseState.action == MouseAction::LButtonDbClick || (states->mouseState.action == MouseAction::LButtonDown && auto_select_all)) { states->activeId = id; if (states->editingId != id) { states->editingId = id; states->stringBuffer = str; } calc_prefix(); states->cursorPos = c_inputTextIndent + (states->stringBuffer.length() > 0 ? states->stringWidthPrefixSum.back() : 0); states->cursorIdx = states->stringBuffer.length(); states->selectIdx = 0; } else if (states->mouseState.action == MouseAction::LButtonDown) { states->activeId = id; if (states->editingId != id) { states->editingId = id; states->stringBuffer = str; } calc_prefix(); const int dist_x = states->mouseState.x - (states->currentPosX + 3); int char_it = std::lower_bound(states->stringWidthPrefixSum.begin(), states->stringWidthPrefixSum.end(), dist_x) - states->stringWidthPrefixSum.begin(); if (--char_it < 0) char_it = 0; states->cursorIdx = char_it; states->cursorPos = c_inputTextIndent + states->stringWidthPrefixSum[char_it]; states->selectIdx = states->cursorIdx; } states->hoveredId = id; } else if (states->mouseState.action == MouseAction::LButtonDown || states->mouseState.action == MouseAction::LButtonDbClick) { if (states->editingId == id) { states->editingId = -1; str = states->stringBuffer; } if (states->activeId == id) states->activeId = -1; } if (states->mouseState.action == MouseAction::Move && states->mouseState.l_down && states->activeId == id) { int dist_x = states->mouseState.x - (states->currentPosX + 3); int char_it = std::lower_bound(states->stringWidthPrefixSum.begin(), states->stringWidthPrefixSum.end(), dist_x) - states->stringWidthPrefixSum.begin(); if (--char_it < 0) char_it = 0; states->cursorIdx = char_it; states->cursorPos = c_inputTextIndent + states->stringWidthPrefixSum[char_it]; } if (states->activeId == id && (states->keyState.funckey != FunctionKey::None || states->keyState.key != '\0')) { switch (states->keyState.funckey) { case FunctionKey::LeftArrow: { auto ori_idx = states->cursorIdx--; if (states->cursorIdx < 0) states->cursorIdx = 0; states->cursorPos += states->stringWidthPrefixSum[states->cursorIdx] - states->stringWidthPrefixSum[ori_idx]; if (states->keyState.keymode != KeyMode::Shift) states->selectIdx = states->cursorIdx; break; } case FunctionKey::RightArrow: { auto ori_idx = states->cursorIdx++; if (states->cursorIdx > (int)states->stringBuffer.length()) states->cursorIdx = states->stringBuffer.length(); states->cursorPos += states->stringWidthPrefixSum[states->cursorIdx] - states->stringWidthPrefixSum[ori_idx]; if (states->keyState.keymode != KeyMode::Shift) states->selectIdx = states->cursorIdx; break; } case FunctionKey::UpArrow: { states->selectIdx = 0; break; } case FunctionKey::DownArrow: { states->selectIdx = states->stringBuffer.length(); break; } case FunctionKey::Enter: { if (states->editingId == id && states->activeId == id) { str = states->stringBuffer; if (auto_clear_on_enter) { states->stringBuffer.clear(); states->cursorIdx = states->selectIdx = 0; states->cursorPos = c_inputTextIndent; calc_prefix(); } else { states->editingId = -1; states->activeId = -1; } } states->selectIdx = states->cursorIdx; break; } case FunctionKey::BackSpace: { if (states->cursorIdx != states->selectIdx) { auto min_idx = states->selectIdx; auto max_idx = states->cursorIdx; if (min_idx > max_idx) std::swap(min_idx, max_idx); states->stringBuffer.erase(min_idx, max_idx - min_idx); states->cursorIdx = min_idx; states->cursorPos = c_inputTextIndent + states->stringWidthPrefixSum[min_idx]; calc_prefix(); } else if (states->cursorIdx > 0) { int shift = states->stringWidthPrefixSum[states->cursorIdx] - states->stringWidthPrefixSum[states->cursorIdx - 1]; states->stringBuffer.erase(states->cursorIdx - 1, 1); calc_prefix(); states->cursorPos -= shift; states->cursorIdx--; } states->selectIdx = states->cursorIdx; break; } case FunctionKey::Delete: { if (states->cursorIdx != states->selectIdx) { auto min_idx = states->selectIdx; auto max_idx = states->cursorIdx; if (min_idx > max_idx) std::swap(min_idx, max_idx); states->stringBuffer.erase(min_idx, max_idx - min_idx); states->cursorIdx = min_idx; states->cursorPos = c_inputTextIndent + states->stringWidthPrefixSum[min_idx]; calc_prefix(); } else if (states->cursorIdx < (int)states->stringBuffer.length()) { int indent = states->stringWidthPrefixSum[states->cursorIdx + 1] - states->stringWidthPrefixSum[states->cursorIdx]; states->stringBuffer.erase(states->cursorIdx, 1); calc_prefix(); } states->selectIdx = states->cursorIdx; break; } case FunctionKey::Home: { states->cursorPos = c_inputTextIndent; states->cursorIdx = 0; states->selectIdx = states->cursorIdx; break; } case FunctionKey::End: { states->cursorPos = states->stringWidthPrefixSum.back() + c_inputTextIndent; states->cursorIdx = states->stringWidthPrefixSum.size() - 1; states->selectIdx = states->cursorIdx; break; } } if (states->keyState.keymode == KeyMode::Ctrl) { switch (states->keyState.key) { case 'A': case 'a': states->selectIdx = 0; states->cursorIdx = states->stringBuffer.length(); states->cursorPos = states->stringWidthPrefixSum.back() + c_inputTextIndent; break; case 'C': case 'c': if (states->cursorIdx != states->selectIdx) { auto min_idx = states->selectIdx; auto max_idx = states->cursorIdx; if (min_idx > max_idx) std::swap(min_idx, max_idx); states->clipboard = states->stringBuffer.substr(min_idx, max_idx - min_idx); } break; case 'X': case 'x': if (states->cursorIdx != states->selectIdx) { auto min_idx = states->selectIdx; auto max_idx = states->cursorIdx; if (min_idx > max_idx) std::swap(min_idx, max_idx); states->clipboard = states->stringBuffer.substr(min_idx, max_idx - min_idx); states->stringBuffer.erase(min_idx, max_idx - min_idx); states->cursorIdx = states->selectIdx = min_idx; states->cursorPos = c_inputTextIndent + states->stringWidthPrefixSum[min_idx]; calc_prefix(); } break; case 'V': case 'v': if (states->clipboard.length()) { auto min_idx = states->selectIdx; auto max_idx = states->cursorIdx; if (min_idx > max_idx) std::swap(min_idx, max_idx); SIZE text_extent; GetTextExtentPoint32A(GuiRenderer::instance()->getHDC(), states->clipboard.c_str(), states->clipboard.length(), &text_extent); if (states->stringWidthPrefixSum.back() + text_extent.cx - (states->stringWidthPrefixSum[max_idx] - states->stringWidthPrefixSum[min_idx]) >= width - c_inputTextIndent) break; if (states->cursorIdx != states->selectIdx) { states->stringBuffer.erase(min_idx, max_idx - min_idx); states->stringBuffer.insert(min_idx, states->clipboard); states->cursorIdx = states->selectIdx = min_idx + states->clipboard.length(); } else { states->stringBuffer.insert(states->cursorIdx, states->clipboard); states->cursorIdx = states->selectIdx = states->cursorIdx + states->clipboard.length(); } calc_prefix(); states->cursorPos = c_inputTextIndent + states->stringWidthPrefixSum[states->cursorIdx]; } break; } } if (states->keyState.keymode == KeyMode::None && (states->keyState.key > 0x2F && states->keyState.key < 0x7F)) { if (states->cursorIdx != states->selectIdx) { auto min_idx = states->selectIdx; auto max_idx = states->cursorIdx; if (min_idx > max_idx) std::swap(min_idx, max_idx); states->stringBuffer.erase(min_idx, max_idx - min_idx); states->cursorIdx = min_idx; states->cursorPos = c_inputTextIndent + states->stringWidthPrefixSum[min_idx]; calc_prefix(); } SIZE text_extent; GetTextExtentPoint32A(GuiRenderer::instance()->getHDC(), &states->keyState.key, 1, &text_extent); if (states->stringWidthPrefixSum.back() + text_extent.cx < width - c_inputTextIndent) { states->stringBuffer.insert(states->cursorIdx, { states->keyState.key }); calc_prefix(); states->cursorPos += text_extent.cx; states->cursorIdx++; states->selectIdx = states->cursorIdx; } } } } else { if (states->activeId == id && states->editingId == id) { str = states->stringBuffer; states->cursorIdx = 0; states->selectIdx = 0; states->cursorPos = c_inputTextIndent; } if (states->activeId == id) states->activeId = -1; if (states->editingId == id) states->editingId = -1; } const Color4f color = banned ? Color4f(1.0f, 1.0f, 1.0f, 0.3f) : states->hoveredId == id && states->activeId == -1 || states->activeId == id ? Color4f(1.0f, 1.0f, 1.0f, 0.65f) : Color4f(1.0f, 1.0f, 1.0f, 0.5f); GuiRenderer::instance()->drawRect(left, top, right, bottom, GuiRenderer::DEPTH_MID, false, color); if (states->hoveredId == id && states->activeId == -1 || states->activeId == id) { glPushAttrib(GL_COLOR_BUFFER_BIT); glBlendFunc(GL_DST_COLOR, GL_CONSTANT_ALPHA); GuiRenderer::instance()->drawRect(left, top, right, bottom, GuiRenderer::DEPTH_MID, true, { 0.6f, 0.6f, 0.6f, 1.0f }); glPopAttrib(); } std::string &rendered_str = states->activeId != id ? str : states->stringBuffer; if (states->selectIdx == states->cursorIdx || states->activeId != id) { if (!banned) glColor4f(1.0f, 1.0f, 1.0f, 1.0f); else glColor4f(1.0f, 1.0f, 1.0f, 0.65f); GuiRenderer::instance()->drawString(states->currentPosX + 3, states->currentPosY + 5, GuiRenderer::DEPTH_MID, rendered_str.c_str()); } else { auto min_idx = states->selectIdx; auto max_idx = states->cursorIdx; if (min_idx > max_idx) std::swap(min_idx, max_idx); GuiRenderer::instance()->drawRect(states->currentPosX + c_inputTextIndent + states->stringWidthPrefixSum[min_idx], states->currentPosY + 3, states->currentPosX + c_inputTextIndent + states->stringWidthPrefixSum[max_idx], states->currentPosY + 16, GuiRenderer::DEPTH_MID, true, color); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); GuiRenderer::instance()->drawString(states->currentPosX + 3, states->currentPosY + 5, GuiRenderer::DEPTH_MID, rendered_str.c_str(), min_idx); GuiRenderer::instance()->drawString(states->currentPosX + 3 + states->stringWidthPrefixSum[max_idx], states->currentPosY + 5, GuiRenderer::DEPTH_MID, rendered_str.c_str() + max_idx); glColor4f(0.15f, 0.15f, 0.15f, 0.15f); glBlendColor(0.0f, 0.0f, 0.0f, 0.0f); GuiRenderer::instance()->drawString(states->currentPosX + 3 + states->stringWidthPrefixSum[min_idx], states->currentPosY + 5, GuiRenderer::DEPTH_MID, rendered_str.c_str() + min_idx, max_idx - min_idx); } if (states->activeId == id) GuiRenderer::instance()->drawLine(states->currentPosX + states->cursorPos, states->currentPosY + 3, states->currentPosX + states->cursorPos, states->currentPosY + 16, GuiRenderer::DEPTH_MID); if (states->currentGrowthStrategy == GrowthStrategy::Vertical) { states->currentPosY += c_inputTextDefaultHeight + c_defaultMarginBottom; states->currentPosX = c_paddingLeft; } else { states->currentPosX += width + c_defaultMarginRight; } } bool AyaGui::InputDigit(const char *label, int &digit, const bool banned) { if (label) Text(label); auto x0 = states->currentPosX, y0 = states->currentPosY; auto prev_digit = digit; states->currentPosX = x0 + 62; if (Button("-", 20, 18, banned)) --digit; states->currentPosX = x0 + 86; states->currentPosY = y0; if (Button("+", 20, 18, banned)) ++digit; states->currentPosX = x0; states->currentPosY = y0; char buf[32]; _itoa_s(digit, buf, 10); std::string str(buf); InputText(str, 60, true, false, banned); digit = atoi(str.c_str()); return digit != prev_digit; } void AyaGui::Scroller(int limit, int actual, float &lin) { int id(states->currentId++); if (actual <= limit) return; states->scrollerActive = true; states->currentPosX = c_paddingLeft; const int bar_base = states->currentPosY; const int diff = 2; const int inner_base = bar_base + diff; float ratio = float(limit) / float(actual); int scroller_len = int(limit * ratio); int scroller_start = int(inner_base + (bar_base - inner_base + limit - diff - scroller_len) * lin); const int scroller_base = inner_base + scroller_len / 2; const int scroller_end = inner_base + limit - scroller_len / 2; int scroller_pos = scroller_base + int((scroller_end - scroller_base) * lin); const int bar_left = states->dialogWidth - c_scrollerMargin; const int bar_top = bar_base; const int bar_right = bar_left + c_scrollerWidth; const int bar_bottom = bar_top + limit; auto SetScroller = [&](int pos) { scroller_pos = pos; if (scroller_pos < scroller_base) scroller_pos = scroller_base; if (scroller_pos > scroller_end) scroller_pos = scroller_end; lin = float(scroller_pos - scroller_base) / (scroller_end - scroller_base); lin = lin < 0.0f ? 0.0f : (lin > 1.0f ? 1.0f : lin); }; if (PtInRect(states->mouseState.x, states->mouseState.y, bar_left, bar_top, bar_right, bar_bottom)) { if (states->mouseState.action == MouseAction::LButtonDown) { states->activeId = id; int offset = states->mouseState.y - scroller_pos; if (offset < 0) offset = -offset; if (offset > scroller_len / 2) states->scrollerBottonDownOffset = 0; else states->scrollerBottonDownOffset = states->mouseState.y - scroller_pos; } if (states->mouseState.action == MouseAction::LButtonUp) { SetScroller(states->mouseState.y - states->scrollerBottonDownOffset); if (states->activeId == id) states->activeId = -1; } states->hoveredId = id; } if (states->mouseState.action == MouseAction::Move && states->mouseState.l_down) { if (states->activeId == id) { SetScroller(states->mouseState.y - states->scrollerBottonDownOffset); } } if (states->mouseState.action == MouseAction::LButtonUp) if (states->activeId == id) states->activeId = -1; const int area_left = 0; const int area_top = bar_base; const int area_right = states->dialogWidth; const int area_bottom = bar_base + limit; if (PtInRect(states->mouseState.x, states->mouseState.y, area_left, area_top, area_right, area_bottom)) { switch (states->keyState.funckey) { case FunctionKey::Home: if (states->activeId == id || states->activeId == -1) SetScroller(scroller_base); break; case FunctionKey::End: if (states->activeId == id || states->activeId == -1) SetScroller(scroller_end); break; case FunctionKey::PageUp: states->activeId = id; SetScroller(scroller_pos - c_pageControlHeight); break; case FunctionKey::PageDown: states->activeId = id; SetScroller(scroller_pos + c_pageControlHeight); break; case FunctionKey::UpArrow: states->activeId = id; SetScroller(scroller_pos - c_arrowControlHeight); break; case FunctionKey::DownArrow: states->activeId = id; SetScroller(scroller_pos + c_arrowControlHeight); break; } } const Color4f color = states->hoveredId == id && states->activeId == -1 || states->activeId == id ? Color4f(1.0f, 1.0f, 1.0f, 0.65f) : Color4f(1.0f, 1.0f, 1.0f, 0.5f); GuiRenderer::instance()->drawRoundedRect(states->dialogWidth - c_scrollerMargin + 1, bar_base, states->dialogWidth - c_scrollerWidth + 1, bar_base + limit, GuiRenderer::DEPTH_MID, diff * 2, false, color); GuiRenderer::instance()->drawRoundedRect(states->dialogWidth - c_scrollerMargin + diff, scroller_start, states->dialogWidth - c_scrollerWidth - 1, scroller_start + scroller_len, GuiRenderer::DEPTH_MID, diff, true, color); } void AyaGui::BeginScroller(int area_height, int &content_height, float &scroller) { glEnable(GL_SCISSOR_TEST); glScissor(states->dialogPosX, states->screenHeight - (states->dialogPosY + states->currentPosY + area_height), states->dialogWidth, area_height); Scroller(area_height, content_height, scroller); int offset = int(scroller * (content_height - area_height)); if (offset < 0) offset = 0; states->scrollerInitY = states->currentPosY - offset; states->scrollerOriginY = states->currentPosY; states->currentPosY = states->scrollerInitY; } void AyaGui::EndScroller(int area_height, int &content_height, float &scroller) { content_height = states->currentPosY - states->scrollerInitY; states->currentPosY = states->scrollerOriginY + area_height + c_defaultMarginBottom; if (states->scrollerActive) { states->currentPosX = c_paddingLeft; states->scrollerActive = false; } glDisable(GL_SCISSOR_TEST); } bool AyaGui::CollapsingHeader(const char *label, bool &show) { const int id(states->currentId++); const int head_left = states->currentPosX; const int head_top = states->currentPosY; const int head_right = states->widgetEndX; const int head_bottom = states->currentPosY + (show ? c_headerTextHeight : c_headerHeight); const bool in_rect = PtInRect(states->mouseState.x, states->mouseState.y, head_left, head_top, head_right, head_bottom); if (in_rect) { if (states->mouseState.action == MouseAction::LButtonDown) states->activeId = id; states->hoveredId = id; } if (states->mouseState.action == MouseAction::LButtonUp) { if (states->activeId == id) { states->activeId = -1; if (in_rect) show = !show; } } glColor4f(1.0f, 1.0f, 1.0f, 1.0f); GuiRenderer::instance()->drawString(states->currentPosX, states->currentPosY, GuiRenderer::DEPTH_MID, label); const Color4f color = states->hoveredId == id && states->activeId == -1 || states->activeId == id ? Color4f(1.0f, 1.0f, 1.0f, 1.0f) : Color4f(1.0f, 1.0f, 1.0f, 0.5f); glColor4fv((float*)&color); GuiRenderer::instance()->drawLine(states->currentPosX, states->currentPosY + c_headerTextHeight + 1, states->widgetEndX, states->currentPosY + c_headerTextHeight + 1, GuiRenderer::DEPTH_MID); if (!show) GuiRenderer::instance()->drawString(states->widgetEndX - 15, states->currentPosY + c_headerTextHeight + 6, GuiRenderer::DEPTH_MID, "..."); states->currentGrowthStrategy = GrowthStrategy::Vertical; states->currentPosY += (!show ? c_headerHeight : c_headerTextHeight) + c_defaultMarginRight; return show; } bool AyaGui::PtInRect(int x0, int y0, int left, int top, int right, int bottom) { return x0 >= left && y0 >= top && x0 < right && y0 < bottom; } }
70,541
C++
.cpp
1,622
39.434032
162
0.707785
g1n0st/AyaGui
38
8
0
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,515
glfwViewer.cpp
g1n0st_AyaGui/src/GUIViewer/glfwViewer.cpp
#include <Gui/Gui.h> #include <GLFW/glfw3.h> #include <iostream> #include <ctime> #include <GUIViewer/Demo.h> using namespace Aya; void InitializeWindowsInfo() { HWND hwnd = GetConsoleWindow(); HGLRC mhRC; HDC mhDC; PIXELFORMATDESCRIPTOR pf = { sizeof(PIXELFORMATDESCRIPTOR), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, PFD_TYPE_RGBA, 24, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 0, 0, PFD_MAIN_PLANE, 0, 0, 0, 0 }; mhDC = GetDC(hwnd); int idx = ChoosePixelFormat(mhDC, &pf); SetPixelFormat(mhDC, idx, &pf); mhRC = wglCreateContext(mhDC); wglMakeCurrent(mhDC, mhRC); } void OnResize(GLFWwindow* window, int width, int height) { AyaGui::Resize(width, height); } void OnKeyboardEvent(GLFWwindow *window, int key, int scancode, int action, int mods) { static KeyboardEvent keyboardEvent; if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) { glfwSetWindowShouldClose(window, true); } if (action == GLFW_PRESS) { switch (key) { case GLFW_KEY_ESCAPE: keyboardEvent.funckey = FunctionKey::Esc; break; case GLFW_KEY_ENTER: keyboardEvent.funckey = FunctionKey::Enter; break; case GLFW_KEY_LEFT: keyboardEvent.funckey = FunctionKey::LeftArrow; break; case GLFW_KEY_RIGHT: keyboardEvent.funckey = FunctionKey::RightArrow; break; case GLFW_KEY_DOWN: keyboardEvent.funckey = FunctionKey::DownArrow; break; case GLFW_KEY_UP: keyboardEvent.funckey = FunctionKey::UpArrow; break; case GLFW_KEY_INSERT: keyboardEvent.funckey = FunctionKey::Insert; break; case GLFW_KEY_BACKSPACE: keyboardEvent.funckey = FunctionKey::BackSpace; break; case GLFW_KEY_DELETE: keyboardEvent.funckey = FunctionKey::Delete; break; case GLFW_KEY_TAB: keyboardEvent.funckey = FunctionKey::Tab; break; case GLFW_KEY_HOME: keyboardEvent.funckey = FunctionKey::Home; break; case GLFW_KEY_END: keyboardEvent.funckey = FunctionKey::End; break; case GLFW_KEY_PAGE_UP: keyboardEvent.funckey = FunctionKey::PageUp; break; case GLFW_KEY_PAGE_DOWN: keyboardEvent.funckey = FunctionKey::PageDown; break; default: keyboardEvent.funckey = FunctionKey::None; } keyboardEvent.key = key; keyboardEvent.keymode = KeyMode::None; if (mods & GLFW_MOD_CONTROL) keyboardEvent.keymode = KeyMode(keyboardEvent.keymode | Ctrl); if (mods & GLFW_MOD_SHIFT) keyboardEvent.keymode = KeyMode(keyboardEvent.keymode | Shift); if (mods & GLFW_MOD_ALT) keyboardEvent.keymode = KeyMode(keyboardEvent.keymode | Alt); } else if (action == GLFW_RELEASE) { keyboardEvent.key = 0; keyboardEvent.funckey = FunctionKey::None; keyboardEvent.keymode = KeyMode::None; } AyaGui::HandleKeyboardEvent(keyboardEvent); } MouseEvent mouseEvent; int lastLeftClick; int lastRightClick; void OnMouseEvent(GLFWwindow *window, int key, int action, int mods) { const int doubleClickInterval = 200; auto keyAction = [&](bool &down, MouseAction &mouse, int &lastClick, const int Mode, const MouseAction DbClock, const MouseAction Down, const MouseAction Up) { if (key == Mode) { if (action == GLFW_PRESS) { down = true; if (std::clock() - lastClick < doubleClickInterval) { lastClick = 0; mouse = DbClock; } else { lastClick = std::clock(); mouse = Down; } } else if (action == GLFW_RELEASE) { down = false; mouse = Up; } } }; keyAction(mouseEvent.l_down, mouseEvent.action, lastLeftClick, GLFW_MOUSE_BUTTON_LEFT, MouseAction::LButtonDbClick, MouseAction::LButtonDown, MouseAction::LButtonUp); keyAction(mouseEvent.r_down, mouseEvent.action, lastRightClick, GLFW_MOUSE_BUTTON_RIGHT, MouseAction::RButtonDbClick, MouseAction::RButtonDown, MouseAction::RButtonUp); AyaGui::HandleMouseEvent(mouseEvent); } void OnCursorEvent(GLFWwindow *window, double x, double y) { if (int(x) != mouseEvent.x || int(y) != mouseEvent.y) { lastLeftClick = 0; lastRightClick = 0; mouseEvent.x = int(x); mouseEvent.y = int(y); } mouseEvent.action = MouseAction::Move; AyaGui::HandleMouseEvent(mouseEvent); } int main() { InitializeWindowsInfo(); InitializeOpenGLExtensions(); glfwInit(); GLFWwindow* window = glfwCreateWindow(1280, 800, "AyaGui glfw Viewer", NULL, NULL); if (window == NULL) { std::cout << "Failed to create GLFW window " << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetKeyCallback(window, OnKeyboardEvent); glfwSetMouseButtonCallback(window, OnMouseEvent); glfwSetCursorPosCallback(window, OnCursorEvent); glViewport(0, 0, 1280, 800); glfwSetFramebufferSizeCallback(window, OnResize); AyaGui::Init(); AyaGui::Resize(1280, 800); while (!glfwWindowShouldClose(window)) { glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); demo_dialog(); glfwSwapBuffers(window); glfwPollEvents(); } AyaGui::Release(); glfwTerminate(); return 0; }
4,880
C++
.cpp
143
31.307692
93
0.740701
g1n0st/AyaGui
38
8
0
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,516
Demo.cpp
g1n0st_AyaGui/src/GUIViewer/Demo.cpp
#include <GUIViewer/demo.h> void about_dialog(int &x, int &y) { static bool is_floating = false; AyaGui::BeginDialog(is_floating ? LayoutStrategy::Floating : LayoutStrategy::Fixed, x, y, "About AyaGui", 500, 430); AyaGui::MultilineText("AyaGui is a lite imgui graphical user interface library in Modern C++ and OpenGL developed by g1n0st, inspired by Dear imgui. \ It is lite, portable and self - contained(no external dependencies) \ You can easily integrate it into your 3D - pipeline enabled application at any time. \n\n\ AyaGui is designed to enable fast iterations and to empower programmers to create content creation tools \ and visualization / debug tools(as opposed to UI for the average end - user). \ It favors simplicity and productivity toward this goal, \ and lacks certain features normally found in more high - level libraries. \n\n\ AyaGui is particularly suited to integration in games engine(for tooling), real - time 3D applications, \ fullscreen applications, embedded applications, or any applications on consoles platforms where operating system features are non - standard. \n\n"); AyaGui::Line(); AyaGui::Text("If you find any issue in AyaGui or require more widgets, "); AyaGui::Text("please post issue on Github, or contact g1n0st: "); AyaGui::Text(Color4f(0.95f, 0.95f, 0.95f, 0.95f), "g1n0st@live.com"); AyaGui::ExpandVertical(); AyaGui::CheckBox("Set it floating", is_floating); AyaGui::EndDialog(); } void test_dialog(int &x, int &y, bool banned) { if (!banned) { AyaGui::BeginDialog(LayoutStrategy::Floating, x, y, "Test Dialog (normal)", 400, 500); } else { AyaGui::BeginDialog(LayoutStrategy::Floating, x, y, "Test Dialog (banned)", 400, 500); } static int content_height; static float scroller; AyaGui::BeginScroller(400, content_height, scroller); AyaGui::Text("Text test"); AyaGui::MultilineText("MultilineText text in line1 \n MultilineText text in line2"); static int hello_num = 0; if (AyaGui::Button("Hello Button", 200, 24, banned)) hello_num++; AyaGui::Text("Hello time: %d", hello_num); static float r = 1.0f, g = 1.0f, b = 1.0f; AyaGui::Horizontal(); AyaGui::Slider<float>("R", r, 0.0f, 1.f, 50, banned); AyaGui::Slider<float>("G", g, 0.0f, 1.f, 50, banned); AyaGui::Slider<float>("B", b, 0.0f, 1.f, 50, banned); AyaGui::ColorBlock(r, g, b); AyaGui::NextLine(60); AyaGui::Vertical(); AyaGui::Text(Color4f(r, g, b, 1.0f), "Colorful Text, r=%.2f, g=%.2f, b=%.2f", r, g, b); AyaGui::NextLine(20); AyaGui::Horizontal(); static float float_val = 0.0f; AyaGui::Slider<float>("Float slider: ", float_val, 0.0f, 100.f, 200, banned); AyaGui::NextLine(25); AyaGui::Horizontal(); static int int_val = 0; AyaGui::Slider<int>("Int slider: ", int_val, 0, 100, 200, banned); AyaGui::NextLine(25); AyaGui::Horizontal(); static char char_val = 0; AyaGui::Slider<char>("Char slider: ", char_val, 'A', 'Z', 200, banned); AyaGui::NextLine(25); AyaGui::Vertical(); static int selected = -1; AyaGui::ComboBox("Combo box", { "Vertex CM", "Multiplex MLT", "Bidirectional PT", "Path Tracing", "Direct Lighting" }, selected, 140, banned); if (selected >= 0) { AyaGui::Text("You selected item id: %d", selected); } else { AyaGui::Text("You have not selected any item yet."); } AyaGui::NextLine(20); static int ratio_val; AyaGui::RadioButton(ratio_val == 1 ? "Option #1 (selected)" : "Option #1", 1, ratio_val, banned); AyaGui::RadioButton(ratio_val == 2 ? "Option #2 (selected)" : "Option #2", 2, ratio_val, banned); AyaGui::RadioButton(ratio_val == 3 ? "Option #2 (selected)" : "Option #2", 3, ratio_val, banned); AyaGui::NextLine(20); static bool checked_1 = false; AyaGui::CheckBox(!checked_1 ? "Check me!" : "Checked 1st Checkbox!", checked_1, banned); static bool checked_2 = false; AyaGui::CheckBox(!checked_2 ? "Check me!" : "Checked 2nd Checkbox!", checked_2, banned); static bool checked_3 = false; AyaGui::CheckBox(!checked_3 ? "Check me!" : "Checked 3rd Checkbox!", checked_3, banned); AyaGui::Text("Input Text: "); static std::string str1; AyaGui::InputText(str1, 200, false, false, banned); static int digit; AyaGui::InputDigit("Input Digit: ", digit, banned); AyaGui::EndScroller(400, content_height, scroller); AyaGui::EndDialog(); } void demo_dialog() { static int about_x = 50, about_y = 50; static int test_x = 600, test_y = 50; static bool showed = false; static bool banned = false; AyaGui::BeginFrame(); AyaGui::BeginSidebarDialog(LayoutStrategy::DockRight); if (AyaGui::CollapsingHeader("Dialog Control Pannel", showed)) { AyaGui::InputDigit("About Dialog Xpos: ", about_x); AyaGui::InputDigit("About Dialog Ypos: ", about_y); AyaGui::InputDigit("Test Dialog Xpos: ", test_x); AyaGui::InputDigit("Test Dialog Ypos: ", test_y); AyaGui::CheckBox("Ban widgets: ", banned); } AyaGui::EndDialog(); about_dialog(about_x, about_y); test_dialog(test_x, test_y, banned); AyaGui::EndFrame(); }
4,979
C++
.cpp
112
42.133929
151
0.706416
g1n0st/AyaGui
38
8
0
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,517
Gui.h
g1n0st_AyaGui/src/Gui/Gui.h
#ifndef AYA_GUI_H #define AYA_GUI_H #include <string> #include <vector> #include <sstream> #include <Windows.h> #include <gl/glew.h> #include <gl/GL.h> #include <gl/GLU.h> namespace Aya { // OpenGL Extension Loader extern PFNGLCREATESHADERPROC glCreateShader; extern PFNGLCREATEPROGRAMPROC glCreateProgram; extern PFNGLDELETESHADERPROC glDeleteShader; extern PFNGLDELETEPROGRAMPROC glDeleteProgram; extern PFNGLATTACHSHADERPROC glAttachShader; extern PFNGLDETACHSHADERPROC glDetachShader; extern PFNGLSHADERSOURCEPROC glShaderSource; extern PFNGLCOMPILESHADERPROC glCompileShader; extern PFNGLLINKPROGRAMPROC glLinkProgram; extern PFNGLVALIDATEPROGRAMPROC glValidateProgram; extern PFNGLUSEPROGRAMPROC glUseProgram; extern PFNGLGETSHADERINFOLOGPROC glGetShaderInfoLog; extern PFNGLGETPROGRAMINFOLOGPROC glGetProgramInfoLog; extern PFNGLGETSHADERIVPROC glGetShaderiv; extern PFNGLGETPROGRAMIVPROC glGetProgramiv; extern PFNGLUNIFORM1FPROC glUniform1f; extern PFNGLUNIFORM1FVPROC glUniform1fv; extern PFNGLUNIFORM2FPROC glUniform2f; extern PFNGLUNIFORM2FVPROC glUniform2fv; extern PFNGLUNIFORM3FPROC glUniform3f; extern PFNGLUNIFORM4FPROC glUniform4f; extern PFNGLUNIFORM1IPROC glUniform1i; extern PFNGLUNIFORM1IVPROC glUniform1iv; extern PFNGLUNIFORM2IPROC glUniform2i; extern PFNGLUNIFORM3IPROC glUniform3i; extern PFNGLUNIFORM4IPROC glUniform4i; extern PFNGLUNIFORMMATRIX3FVPROC glUniformMatrix3fv; extern PFNGLUNIFORMMATRIX4FVPROC glUniformMatrix4fv; extern PFNGLGETUNIFORMLOCATIONPROC glGetUniformLocation; extern PFNGLBINDFRAGDATALOCATIONEXTPROC glBindFragDataLocation; extern PFNGLISRENDERBUFFEREXTPROC glIsRenderbuffer; extern PFNGLBINDRENDERBUFFEREXTPROC glBindRenderbuffer; extern PFNGLDELETERENDERBUFFERSEXTPROC glDeleteRenderbuffers; extern PFNGLGENRENDERBUFFERSEXTPROC glGenRenderbuffers; extern PFNGLRENDERBUFFERSTORAGEEXTPROC glRenderbufferStorage; extern PFNGLRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC glRenderbufferStorageMultisample; extern PFNGLGETRENDERBUFFERPARAMETERIVEXTPROC glGetRenderbufferParameteriv; extern PFNGLISFRAMEBUFFEREXTPROC glIsFramebuffer; extern PFNGLBINDFRAMEBUFFEREXTPROC glBindFramebuffer; extern PFNGLDELETEFRAMEBUFFERSEXTPROC glDeleteFramebuffers; extern PFNGLGENFRAMEBUFFERSEXTPROC glGenFramebuffers; extern PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC glCheckFramebufferStatus; extern PFNGLFRAMEBUFFERTEXTURE1DEXTPROC glFramebufferTexture1D; extern PFNGLFRAMEBUFFERTEXTURE2DEXTPROC glFramebufferTexture2D; extern PFNGLFRAMEBUFFERTEXTURE3DEXTPROC glFramebufferTexture3D; extern PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC glFramebufferRenderbuffer; extern PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVEXTPROC glGetFramebufferAttachmentParameteriv; extern PFNGLBLITFRAMEBUFFEREXTPROC glBlitFramebuffer; extern PFNGLGENERATEMIPMAPEXTPROC glGenerateMipmap; extern PFNGLDRAWBUFFERSPROC glDrawBuffers; extern PFNGLDRAWRANGEELEMENTSPROC glDrawRangeElements; extern PFNGLACTIVETEXTUREPROC glActiveTexture; extern PFNGLCLIENTACTIVETEXTUREPROC glClientActiveTexture; extern PFNGLMULTITEXCOORD1FPROC glMultiTexcoord1f; extern PFNGLMULTITEXCOORD2FPROC glMultiTexcoord2f; extern PFNGLMULTITEXCOORD3FPROC glMultiTexcoord3f; extern PFNGLMULTITEXCOORD4FPROC glMultiTexcoord4f; extern PFNGLLOADTRANSPOSEMATRIXFPROC glLoadTransposeMatrixf; extern PFNGLBINDBUFFERPROC glBindBuffer; extern PFNGLBUFFERDATAPROC glBufferData; extern PFNGLBUFFERSUBDATAPROC glBufferSubData; extern PFNGLDELETEBUFFERSPROC glDeleteBuffers; extern PFNGLGENBUFFERSPROC glGenBuffers; extern PFNGLMAPBUFFERPROC glMapBuffer; extern PFNGLUNMAPBUFFERPROC glUnmapBuffer; extern PFNGLBLENDEQUATIONPROC glBlendEquation; extern PFNGLBLENDCOLORPROC glBlendColor; extern PFNGLBLENDFUNCSEPARATEPROC glBlendFuncSeperate; extern PFNGLBLENDEQUATIONSEPARATEPROC glBlendEquationSeperate; void InitializeOpenGLExtensions(); struct Color4f { GLfloat r, g, b, a; Color4f() = default; Color4f(GLfloat r0, GLfloat g0, GLfloat b0, GLfloat a0 = 1.0f) noexcept : r(r0), g(g0), b(b0), a(a0) { } }; class GuiRenderer { private: static GuiRenderer *mp_instance; GLint m_textListBase; GLint m_width, m_height; HDC m_HDC; GLuint m_handleProgram; GLuint m_handleBackgroundTex; GLuint m_handleFBO; GLuint m_handleColorRBO; // Gaussian blur weights and offsets static const size_t BLUR_SAMPLE = 13; GLfloat m_gaussianWeights[BLUR_SAMPLE]; GLfloat m_gaussianOffsets[BLUR_SAMPLE * 2]; // Precomputed coordinates for circle static const size_t CIRCLE_VERTEX_COUNT = 24; GLfloat m_circleCoords[CIRCLE_VERTEX_COUNT * 2]; static const GLchar *s_vertShaderSource; static const GLchar *s_blurFragShaderSource; public: static const GLfloat DEPTH_FAR; static const GLfloat DEPTH_MID; static const GLfloat DEPTH_NEAR; private: GuiRenderer(); ~GuiRenderer(); public: static __forceinline GuiRenderer* instance() { if (!mp_instance) mp_instance = new GuiRenderer; return mp_instance; } static void deleteInstance() { if (!mp_instance) { delete mp_instance; mp_instance = nullptr; } } __forceinline HDC getHDC() const { return m_HDC; } void resize(int width, int height); // Draw Call void blurBackgroundTexture(int x0, int y0, int x1, int y1); void drawBackgroundTexture(int x0, int y0, int x1, int y1); void drawLine(int x0, int y0, int x1, int y1, float depth) const; void drawRect(int x0, int y0, int x1, int y1, float depth, const bool filled = false, const Color4f &color = Color4f(1.0f, 1.0f, 1.0f, 0.5f), const Color4f &blend_color = Color4f(0.f, 0.f, 0.f, 0.f)) const; void drawRoundedRect(int x0, int y0, int x1, int y1, float depth, float radius, const bool filled = false, const Color4f &color = Color4f(1.0f, 1.0f, 1.0f, 0.5f), const Color4f &blend_color = Color4f(0.f, 0.f, 0.f, 0.f)) const; void drawHalfRoundedRect(int x0, int y0, int x1, int y1, float depth, float radius, const bool filled = false, const Color4f &color = Color4f(1.0f, 1.0f, 1.0f, 0.5f), const Color4f &blend_color = Color4f(0.f, 0.f, 0.f, 0.f)) const; void drawCircle(int x0, int y0, float depth, int radius, bool filled, const Color4f &color) const; void drawString(int x0, int y0, float depth, const char *text, int length = -1) const; private: void CalcGaussianBlurWeightsAndOffsets(); }; // Immediate Mode GUI enum class LayoutStrategy { DockLeft, DockRight, Floating, Fixed }; enum class GrowthStrategy { Vertical, Horizontal }; enum class MouseAction { None, LButtonDown, LButtonUp, LButtonDbClick, RButtonDown, RButtonUp, RButtonDbClick, Move }; struct MouseEvent { int x, y; bool l_down, r_down; MouseAction action; }; enum class FunctionKey { None, Esc, Enter, LeftArrow, UpArrow, RightArrow, DownArrow, PageUp, PageDown, Insert, BackSpace, Delete, Tab, Home, End }; enum KeyMode { None = 0, Ctrl = 1 << 0, Shift = 1 << 1, Alt = 1 << 2, CtrlShift = Ctrl | Shift, CtrlAlt = Ctrl | Alt, ShiftAlt = Shift | Alt, CtrlShiftAlt = Ctrl | Shift | Alt }; struct KeyboardEvent { KeyMode keymode; char key; FunctionKey funckey; }; struct GuiStates { int screenWidth; int screenHeight; int dialogPosX; int dialogPosY; int dialogWidth; int dialogHeight; int currentPosX; int currentPosY; int widgetEndX; LayoutStrategy currentLayoutStrategy; GrowthStrategy currentGrowthStrategy; int currentId; int hoveredId; int activeId; int currentDialogId; int activeDialogId; int movingId; MouseEvent mouseState; MouseEvent prevGlobalMouseState; MouseEvent globalMouseState; KeyboardEvent keyState; // Text edit states int editingId; int cursorPos; int cursorIdx; int selectIdx; std::string stringBuffer; std::vector<int> stringWidthPrefixSum; std::string clipboard; // Scroller states int scrollerInitY; int scrollerOriginY; int scrollerBottonDownOffset; bool scrollerActive; }; class AyaGui { private: static GuiStates *states; static const int c_defaultMarginBottom = 10; static const int c_defaultMarginRight = 5; static const int c_lineMarginBottom = 8; static const int c_paddingLeft = 18; static const int c_sidebarPaddingTop = 24; static const int c_titledDialogPaddingTop = 32; static const int c_untitledDialogPaddingTop = 12; static const int c_sidebarWidth = 200; static const int c_dialogTitleHeight = 24; static const int c_textHeight = 10; static const int c_multilineTextHeight = 16; static const int c_buttonDefaultHeight = 24; static const int c_comboBoxDefaultWidth = 140; static const int c_comboBoxHeight = 18; static const int c_comboBoxItemHeight = 20; static const int c_checkBoxSize = 12; static const int c_radioButtonCircleDiameter = 12; static const int c_scrollerWidth = 8; static const int c_scrollerMargin = 15; static const int c_pageControlHeight = 50; static const int c_arrowControlHeight = 20; static const int c_sliderDefaultHeight = 14; static const int c_sliderDefaultWidth = 140; static const int c_sliderButtonDefaultWidth = 7; static const int c_defaultColorBlockSize = 32; static const int c_inputTextDefaultWidth = 100; static const int c_inputTextDefaultHeight = 18; static const int c_inputTextIndent = 4; static const int c_headerHeight = 30; static const int c_headerTextHeight = 11; public: static void Init(); static void Release(); static void Resize(int width, int height); static void Vertical(); static void Horizontal(); static void ExpandVertical(int margin = c_defaultMarginBottom); static void ExpandHorizontal(int margin = c_defaultMarginRight); static void NextLine(int margin = c_defaultMarginBottom, int padding = c_paddingLeft); static void Target(int x, int y); static void BeginFrame(); static void EndFrame(); static void BeginDialog(LayoutStrategy layout, int &x, int &y, const char *title = nullptr, const int width = 250, const int height = 500, GrowthStrategy growth_strategy = GrowthStrategy::Vertical); static void BeginSidebarDialog(LayoutStrategy layout, const int width = 250, const int height = 500, GrowthStrategy growth_strategy = GrowthStrategy::Vertical); static void EndDialog(); static bool HandleMouseEvent(const MouseEvent& mouseArgs); static bool HandleKeyboardEvent(const KeyboardEvent& keyArgs); static void Text(const char *str, ...); static void Text(Color4f color, const char *str, ...); static void MultilineText(const char *str, ...); static bool Button(const char *label, const int width = 114514, const int height = c_buttonDefaultHeight, const bool banned = false); static void Line(); static void ComboBox(const char *label, const std::vector<std::string> items, int &selected, const int width = c_comboBoxDefaultWidth, const bool banned = false); static bool CheckBox(const char *label, bool &checked, const bool banned = false); static bool RadioButton(const char *label, int active, int &current, const bool banned = false); static void ColorBlock(float r, float g, float b, const int size = c_defaultColorBlockSize); static void InputText(std::string &str, const int width = c_inputTextDefaultWidth, const bool auto_select_all = false, const bool auto_clear_on_enter = false, const bool banned = false); static bool InputDigit(const char *label, int &digit, const bool banned = false); static void Scroller(int limit, int actual, float &lin); static void BeginScroller(int area_height, int &content_height, float &scroller); static void EndScroller(int area_height, int &content_height, float &scroller); static bool CollapsingHeader(const char *label, bool &show); template<typename T> static bool Slider(const char *label, T &val, T min, T max, int width = c_sliderDefaultWidth, const bool banned = false) { const int id(states->currentId++); bool modified = false; if (label) Text(label); if (width > states->widgetEndX - states->currentPosX) width = states->widgetEndX - states->currentPosX; const int slider_base = states->currentPosX + c_sliderButtonDefaultWidth; const int slider_end = states->currentPosX + width - c_sliderButtonDefaultWidth; auto fix01 = [](float val, float min, float max) { if (min == max) return 0.0f; float value = (val - min) / (max - min); if (value < 0.0f) return 0.0f; if (value > 1.0f) return 1.0f; return value; }; auto fix = [](int val, int min, int max) { if (val < min) return min; if (val > max) return max; return val; }; const float lin = fix01(float(val), float(min), float(max)); int button_x = int(slider_base + (slider_end - slider_base) * lin); const int bar_left = states->currentPosX; const int bar_top = states->currentPosY; const int bar_right = bar_left + width; const int bar_bottom = bar_top + c_sliderDefaultHeight; if (!banned) { if (PtInRect(states->mouseState.x, states->mouseState.y, bar_left, bar_top, bar_right, bar_bottom)) { if (states->mouseState.action == MouseAction::LButtonDown) states->activeId = id; if (states->mouseState.action == MouseAction::LButtonUp) { if (states->activeId == id) { button_x = fix(states->mouseState.x, slider_base, slider_end); float btn_lin = fix01(float(button_x), float(slider_base), float(slider_end)); val = T(min + (max - min) * btn_lin); float lin = fix01(float(val), float(min), float(max)); button_x = int(slider_base + (slider_end - slider_base) * lin); modified = true; states->activeId = -1; } } states->hoveredId = id; } if (states->mouseState.action == MouseAction::Move && states->mouseState.l_down) { if (states->activeId == id) { button_x = fix(states->mouseState.x, slider_base, slider_end); float btn_lin = fix01(float(button_x), float(slider_base), float(slider_end)); val = T(min + (max - min) * btn_lin); float lin = fix01(float(val), float(min), float(max)); button_x = int(slider_base + (slider_end - slider_base) * lin); modified = true; } } } else { if (states->activeId == id) states->activeId = -1; } if (states->mouseState.action == MouseAction::LButtonUp) if (states->activeId == id) states->activeId = -1; const Color4f color1 = banned ? Color4f(1.0f, 1.0f, 1.0f, 0.3f) : states->hoveredId == id && states->activeId == -1 || states->hoveredId == id ? Color4f(1.0f, 1.0f, 1.0f, 0.65f) : Color4f(1.0f, 1.0f, 1.0f, 0.5f); const Color4f color2 = banned ? Color4f(0.15f, 0.15f, 0.15f, 0.3f) : states->hoveredId == id && states->activeId == -1 || states->hoveredId == id ? Color4f(0.3f, 0.3f, 0.3f, 0.65f) : Color4f(0.15f, 0.15f, 0.15f, 0.5f); GuiRenderer::instance()->drawRect(bar_left - 1, bar_top - 1, bar_right + 1, bar_bottom + 1, GuiRenderer::DEPTH_MID, false, banned ? Color4f(1.0f, 1.0f, 1.0f, 0.65f) : Color4f(1.0f, 1.0f, 1.0f, 1.0f)); GuiRenderer::instance()->drawRect(bar_left, bar_top, bar_right, bar_bottom, GuiRenderer::DEPTH_MID, true, color2, Color4f(1.0f, 1.0f, 1.0f, 0.6f)); GuiRenderer::instance()->drawRect(button_x - c_sliderButtonDefaultWidth, bar_top, button_x + c_sliderButtonDefaultWidth, bar_bottom, GuiRenderer::DEPTH_MID, true, color1); { std::stringstream text_stream; text_stream.setf(std::ios::fixed); text_stream.precision(2); text_stream << val; std::string str_val; text_stream >> str_val; const char *str = str_val.c_str(); SIZE text_extent; GetTextExtentPoint32A(GuiRenderer::instance()->getHDC(), str, strlen(str), &text_extent); if (!banned) glColor4f(1.0f, 1.0f, 1.0f, 1.0f); else glColor4f(1.0f, 1.0f, 1.0f, 0.65f); GuiRenderer::instance()->drawString(bar_left + width / 2 - text_extent.cx / 2, bar_top + c_sliderButtonDefaultWidth - 4, GuiRenderer::DEPTH_MID, str); } if (states->currentGrowthStrategy == GrowthStrategy::Vertical) { states->currentPosY += c_checkBoxSize + c_defaultMarginBottom; states->currentPosX = c_paddingLeft; } else { states->currentPosX += width + c_defaultMarginRight; } return 0; } private: static bool PtInRect(int x0, int y0, int left, int top, int right, int bottom); }; } #endif
16,831
C++
.h
413
37.31477
154
0.733664
g1n0st/AyaGui
38
8
0
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,518
Demo.h
g1n0st_AyaGui/src/GUIViewer/Demo.h
#pragma once #include <Gui/Gui.h> using namespace Aya; void about_dialog(int &x, int &y); void test_dialog(int &x, int &y, bool banned = false); void demo_dialog();
166
C++
.h
6
26.5
54
0.72327
g1n0st/AyaGui
38
8
0
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,521
can1.h
atc1441_CustomCanDecoderBox/BLuePillCanWithSleepMCP2515/can1.h
#ifndef CAN_H_ #define CAN_H_ #include <stdint.h> typedef unsigned char __u8; typedef unsigned short __u16; typedef unsigned long __u32; /* special address description flags for the CAN_ID */ #define CAN_EFF_FLAG 0x80000000UL /* EFF/SFF is set in the MSB */ #define CAN_RTR_FLAG 0x40000000UL /* remote transmission request */ #define CAN_ERR_FLAG 0x20000000UL /* error message frame */ /* valid bits in CAN ID for frame formats */ #define CAN_SFF_MASK 0x000007FFUL /* standard frame format (SFF) */ #define CAN_EFF_MASK 0x1FFFFFFFUL /* extended frame format (EFF) */ #define CAN_ERR_MASK 0x1FFFFFFFUL /* omit EFF, RTR, ERR flags */ /* * Controller Area Network Identifier structure * * bit 0-28 : CAN identifier (11/29 bit) * bit 29 : error message frame flag (0 = data frame, 1 = error message) * bit 30 : remote transmission request flag (1 = rtr frame) * bit 31 : frame format flag (0 = standard 11 bit, 1 = extended 29 bit) */ typedef __u32 canid_t; #define CAN_SFF_ID_BITS 11 #define CAN_EFF_ID_BITS 29 /* CAN payload length and DLC definitions according to ISO 11898-1 */ #define CAN_MAX_DLC 8 #define CAN_MAX_DLEN 8 struct can_frame { canid_t can_id; /* 32 bit CAN_ID + EFF/RTR/ERR flags */ __u8 can_dlc; /* frame payload length in byte (0 .. CAN_MAX_DLEN) */ __u8 data[CAN_MAX_DLEN] __attribute__((aligned(8))); }; #endif /* CAN_H_ */
1,439
C++
.h
34
39.117647
76
0.683297
atc1441/CustomCanDecoderBox
38
8
3
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,523
WiFiServer_Generic.cpp
khoih-prog_WiFiNINA_Generic/src/WiFiServer_Generic.cpp
/********************************************************************************************************************************** WiFiServer_Generic.cpp - Library for Arduino WiFiNINA module/shield. Based on and modified from WiFiNINA library https://www.arduino.cc/en/Reference/WiFiNINA to support nRF52, SAMD21/SAMD51, STM32F/L/H/G/WB/MP1, Teensy, etc. boards besides Nano-33 IoT, MKRWIFI1010, MKRVIDOR400, etc. Built by Khoi Hoang https://github.com/khoih-prog/WiFiNINA_Generic Licensed under MIT license Copyright (c) 2018 Arduino SA. All rights reserved. Copyright (c) 2011-2014 Arduino LLC. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Version: 1.8.15-1 Version Modified By Date Comments ------- ----------- ---------- ----------- 1.5.0 K Hoang 27/03/2020 Initial coding to support other boards besides Nano-33 IoT, MKRWIFI1010, MKRVIDOR4000, etc. such as Arduino Mega, Teensy, SAMD21, SAMD51, STM32, etc ... 1.8.13 K Hoang 03/08/2021 Sync with WiFiNINA v1.8.13 : new FW v1.4.8. Add support to ADAFRUIT_MATRIXPORTAL_M4_EXPRESS 1.8.14-1 K Hoang 25/11/2021 Fix examples to support ATmega4809 such as UNO_WIFI_REV2 and NANO_EVERY 1.8.14-2 K Hoang 31/12/2021 Add support to Nano_RP2040_Connect using arduino-pico core 1.8.14-3 K Hoang 31/12/2021 Fix issue with UDP for Nano_RP2040_Connect using arduino-pico core 1.8.14-4 K Hoang 01/05/2022 Fix bugs by using some PRs from original WiFiNINA. Add WiFiMulti-related examples 1.8.14-5 K Hoang 23/05/2022 Fix bug causing data lost when sending large files 1.8.14-6 K Hoang 17/08/2022 Add support to Teensy 4.x using WiFiNINA AirLift. Fix minor bug 1.8.14-7 K Hoang 11/11/2022 Modify WiFiWebServer example to avoid crash in arduino-pico core 1.8.15-0 K Hoang 14/11/2022 Fix severe limitation to permit sending much larger data than total 4K 1.8.15-1 K Hoang 18/11/2022 Using new WiFi101_Generic library to permit sending larger data than total 4K ***********************************************************************************************************************************/ #include <string.h> #include "utility/server_drv.h" #define _WIFININA_LOGLEVEL_ 1 //////////////////////////////////////// extern "C" { #include "utility/debug.h" } #include "WiFi_Generic.h" #include "WiFiClient_Generic.h" #include "WiFiServer_Generic.h" //////////////////////////////////////// // See Version 1.4.0 can break code that uses more than one WiFiServer and socket // (https://github.com/arduino-libraries/WiFiNINA/issues/87 #if USING_MULTI_SERVER_ISSUE_FIX WiFiServer::WiFiServer(uint16_t port) : _sock(NO_SOCKET_AVAIL) #else WiFiServer::WiFiServer(uint16_t port) : _sock(NO_SOCKET_AVAIL), _lastSock(NO_SOCKET_AVAIL) #endif { _port = port; } //////////////////////////////////////// void WiFiServer::begin() { _sock = ServerDrv::getSocket(); if (_sock != NO_SOCKET_AVAIL) { ServerDrv::startServer(_port, _sock); } } //////////////////////////////////////// // From https://github.com/arduino-libraries/WiFiNINA/pull/204 WiFiClient WiFiServer::accept() { int sock = ServerDrv::availServer(_sock, true); return WiFiClient(sock); } //////////////////////////////////////// void WiFiServer::begin(uint16_t port) { _port = port; begin(); } //////////////////////////////////////// WiFiClient WiFiServer::available(byte* status) { int sock = NO_SOCKET_AVAIL; if (_sock != NO_SOCKET_AVAIL) { // See Version 1.4.0 can break code that uses more than one WiFiServer and socket // (https://github.com/arduino-libraries/WiFiNINA/issues/87 #if USING_MULTI_SERVER_ISSUE_FIX sock = ServerDrv::availServer(_sock); #else // check previous received client socket if (_lastSock != NO_SOCKET_AVAIL) { WiFiClient client(_lastSock); // KH, from v1.6.0 debug NN_LOGDEBUG1("WiFiServer::available: _lastSock =", _lastSock); if (client.connected()) NN_LOGDEBUG("WiFiServer::available: client.connected"); if (client.available()) NN_LOGDEBUG("WiFiServer::available: client.available"); if (client.connected() && client.available()) { sock = _lastSock; } } if (sock == NO_SOCKET_AVAIL) { // check for new client socket sock = ServerDrv::availServer(_sock); } #endif } if (sock != NO_SOCKET_AVAIL) { WiFiClient client(sock); if (status != NULL) { *status = client.status(); } // See Version 1.4.0 can break code that uses more than one WiFiServer and socket // (https://github.com/arduino-libraries/WiFiNINA/issues/87 #if !USING_MULTI_SERVER_ISSUE_FIX _lastSock = sock; #endif return client; } return WiFiClient(255); } //////////////////////////////////////// uint8_t WiFiServer::status() { if (_sock == NO_SOCKET_AVAIL) { return CLOSED; } else { return ServerDrv::getServerState(_sock); } } //////////////////////////////////////// size_t WiFiServer::write(uint8_t b) { return write(&b, 1); } //////////////////////////////////////// #define WIFI_SERVER_MAX_WRITE_RETRY 100 // Don't use larger size or hang #define WIFI_SERVER_SEND_MAX_SIZE 4032 size_t WiFiServer::write(const uint8_t *buf, size_t size) { int written = 0; int retry = WIFI_SERVER_SEND_MAX_SIZE; size_t totalBytesSent = 0; size_t bytesRemaining = size; NN_LOGDEBUG1("WiFiServer::write: To write, size = ", size); if (_sock == NO_SOCKET_AVAIL) { setWriteError(); NN_LOGERROR("WiFiServer::write: NO_SOCKET_AVAIL"); return 0; } if (size == 0) { setWriteError(); NN_LOGDEBUG("WiFiServer::write: size = 0"); return 0; } while (retry) { written = ServerDrv::sendData(_sock, buf, min(bytesRemaining, WIFI_SERVER_SEND_MAX_SIZE) ); if (written > 0) { totalBytesSent += written; NN_LOGDEBUG3("WiFiServer::write: written = ", written, ", totalBytesSent =", totalBytesSent); if (totalBytesSent >= size) { NN_LOGDEBUG3("WiFiServer::write: Done, written = ", written, ", totalBytesSent =", totalBytesSent); //completed successfully retry = 0; } else { buf += written; bytesRemaining -= written; retry = WIFI_SERVER_MAX_WRITE_RETRY; // Don't use too short delay so that NINA has some time to recover // The fix is considered as kludge, and the correct place to fix is in ServerDrv::sendData() //delay(100); NN_LOGDEBUG3("WiFiServer::write: Partially Done, written = ", written, ", bytesRemaining =", bytesRemaining); } } else if (written < 0) { NN_LOGERROR("WiFiServer::write: written error"); // close socket ServerDrv::stopClient(_sock); written = 0; retry = 0; } // Looping } if (!ServerDrv::checkDataSent(_sock)) { setWriteError(); NN_LOGDEBUG("WiFiServer::write: error !checkDataSent"); return 0; } if (totalBytesSent >= size) { NN_LOGDEBUG1("WiFiServer::write: OK, totalBytesSent = ", totalBytesSent); } else { NN_LOGERROR3("WiFiServer::write: Not OK, size = ", size, ", totalBytesSent = ", totalBytesSent); } return totalBytesSent; } ////////////////////////////////////////
8,091
C++
.cpp
220
32.695455
133
0.628286
khoih-prog/WiFiNINA_Generic
36
12
0
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,534
defines.h
khoih-prog_WiFiNINA_Generic/examples/WiFiWebServer_BigData/defines.h
/**************************************************************************************************************************** defines.h For boards with WiFiNINA module/shield. Based on and modified from WiFiNINA library https://www.arduino.cc/en/Reference/WiFiNINA to support nRF52, SAMD21/SAMD51, STM32F/L/H/G/WB/MP1, Teensy, etc. boards besides Nano-33 IoT, MKRWIFI1010, MKRVIDOR400, etc. Built by Khoi Hoang https://github.com/khoih-prog/WiFiNINA_Generic Licensed under MIT license Copyright (c) 2018 Arduino SA. All rights reserved. Copyright (c) 2011-2014 Arduino LLC. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA *****************************************************************************************************************************/ #ifndef defines_h #define defines_h #if ( defined(ARDUINO_SAMD_ZERO) || defined(ARDUINO_SAMD_MKR1000) || defined(ARDUINO_SAMD_MKRWIFI1010) \ || defined(ARDUINO_SAMD_NANO_33_IOT) || defined(ARDUINO_SAMD_MKRFox1200) || defined(ARDUINO_SAMD_MKRWAN1300) || defined(ARDUINO_SAMD_MKRWAN1310) \ || defined(ARDUINO_SAMD_MKRGSM1400) || defined(ARDUINO_SAMD_MKRNB1500) || defined(ARDUINO_SAMD_MKRVIDOR4000) \ || defined(ARDUINO_SAMD_CIRCUITPLAYGROUND_EXPRESS) || defined(__SAMD51__) || defined(__SAMD51J20A__) \ || defined(__SAMD51J19A__) || defined(__SAMD51G19A__) || defined(__SAMD51P19A__) \ || defined(__SAMD21E15A__) || defined(__SAMD21E16A__) || defined(__SAMD21E17A__) || defined(__SAMD21E18A__) \ || defined(__SAMD21G15A__) || defined(__SAMD21G16A__) || defined(__SAMD21G17A__) || defined(__SAMD21G18A__) \ || defined(__SAMD21J15A__) || defined(__SAMD21J16A__) || defined(__SAMD21J17A__) || defined(__SAMD21J18A__) ) #if defined(WIFININA_USE_SAMD) #undef WIFININA_USE_SAMD #endif #define WIFININA_USE_SAMD true #endif #if defined(WIFININA_USE_SAMD) #if defined(ARDUINO_SAMD_ZERO) #define BOARD_TYPE "SAMD Zero" #elif defined(ARDUINO_SAMD_MKR1000) #define BOARD_TYPE "SAMD MKR1000" #elif defined(ARDUINO_SAMD_MKRWIFI1010) #define BOARD_TYPE "SAMD MKRWIFI1010" #elif defined(ARDUINO_SAMD_NANO_33_IOT) #define BOARD_TYPE "SAMD NANO_33_IOT" #elif defined(ARDUINO_SAMD_MKRFox1200) #define BOARD_TYPE "SAMD MKRFox1200" #elif ( defined(ARDUINO_SAMD_MKRWAN1300) || defined(ARDUINO_SAMD_MKRWAN1310) ) #define BOARD_TYPE "SAMD MKRWAN13X0" #elif defined(ARDUINO_SAMD_MKRGSM1400) #define BOARD_TYPE "SAMD MKRGSM1400" #elif defined(ARDUINO_SAMD_MKRNB1500) #define BOARD_TYPE "SAMD MKRNB1500" #elif defined(ARDUINO_SAMD_MKRVIDOR4000) #define BOARD_TYPE "SAMD MKRVIDOR4000" #elif defined(ARDUINO_SAMD_CIRCUITPLAYGROUND_EXPRESS) #define BOARD_TYPE "SAMD ARDUINO_SAMD_CIRCUITPLAYGROUND_EXPRESS" #elif defined(ADAFRUIT_FEATHER_M0_EXPRESS) #define BOARD_TYPE "SAMD21 ADAFRUIT_FEATHER_M0_EXPRESS" #elif defined(ADAFRUIT_METRO_M0_EXPRESS) #define BOARD_TYPE "SAMD21 ADAFRUIT_METRO_M0_EXPRESS" #elif defined(ADAFRUIT_CIRCUITPLAYGROUND_M0) #define BOARD_TYPE "SAMD21 ADAFRUIT_CIRCUITPLAYGROUND_M0" #elif defined(ADAFRUIT_GEMMA_M0) #define BOARD_TYPE "SAMD21 ADAFRUIT_GEMMA_M0" #elif defined(ADAFRUIT_TRINKET_M0) #define BOARD_TYPE "SAMD21 ADAFRUIT_TRINKET_M0" #elif defined(ADAFRUIT_ITSYBITSY_M0) #define BOARD_TYPE "SAMD21 ADAFRUIT_ITSYBITSY_M0" #elif defined(ARDUINO_SAMD_HALLOWING_M0) #define BOARD_TYPE "SAMD21 ARDUINO_SAMD_HALLOWING_M0" #elif defined(ADAFRUIT_METRO_M4_EXPRESS) #define BOARD_TYPE "SAMD51 ADAFRUIT_METRO_M4_EXPRESS" #elif defined(ADAFRUIT_GRAND_CENTRAL_M4) #define BOARD_TYPE "SAMD51 ADAFRUIT_GRAND_CENTRAL_M4" #elif defined(ADAFRUIT_FEATHER_M4_EXPRESS) #define BOARD_TYPE "SAMD51 ADAFRUIT_FEATHER_M4_EXPRESS" #elif defined(ADAFRUIT_ITSYBITSY_M4_EXPRESS) #define BOARD_TYPE "SAMD51 ADAFRUIT_ITSYBITSY_M4_EXPRESS" #elif defined(ADAFRUIT_TRELLIS_M4_EXPRESS) #define BOARD_TYPE "SAMD51 ADAFRUIT_TRELLIS_M4_EXPRESS" #elif defined(ADAFRUIT_PYPORTAL) #define BOARD_TYPE "SAMD51 ADAFRUIT_PYPORTAL" #elif defined(ADAFRUIT_PYPORTAL_M4_TITANO) #define BOARD_TYPE "SAMD51 ADAFRUIT_PYPORTAL_M4_TITANO" #elif defined(ADAFRUIT_PYBADGE_M4_EXPRESS) #define BOARD_TYPE "SAMD51 ADAFRUIT_PYBADGE_M4_EXPRESS" #elif defined(ADAFRUIT_METRO_M4_AIRLIFT_LITE) #define BOARD_TYPE "SAMD51 ADAFRUIT_METRO_M4_AIRLIFT_LITE" #elif defined(ADAFRUIT_PYGAMER_M4_EXPRESS) #define BOARD_TYPE "SAMD51 ADAFRUIT_PYGAMER_M4_EXPRESS" #elif defined(ADAFRUIT_PYGAMER_ADVANCE_M4_EXPRESS) #define BOARD_TYPE "SAMD51 ADAFRUIT_PYGAMER_ADVANCE_M4_EXPRESS" #elif defined(ADAFRUIT_PYBADGE_AIRLIFT_M4) #define BOARD_TYPE "SAMD51 ADAFRUIT_PYBADGE_AIRLIFT_M4" #elif defined(ADAFRUIT_MONSTER_M4SK_EXPRESS) #define BOARD_TYPE "SAMD51 ADAFRUIT_MONSTER_M4SK_EXPRESS" #elif defined(ADAFRUIT_HALLOWING_M4_EXPRESS) #define BOARD_TYPE "SAMD51 ADAFRUIT_HALLOWING_M4_EXPRESS" #elif defined(SEEED_WIO_TERMINAL) #define BOARD_TYPE "SAMD SEEED_WIO_TERMINAL" #elif defined(SEEED_FEMTO_M0) #define BOARD_TYPE "SAMD SEEED_FEMTO_M0" #elif defined(SEEED_XIAO_M0) #define BOARD_TYPE "SAMD SEEED_XIAO_M0" #elif defined(Wio_Lite_MG126) #define BOARD_TYPE "SAMD SEEED Wio_Lite_MG126" #elif defined(WIO_GPS_BOARD) #define BOARD_TYPE "SAMD SEEED WIO_GPS_BOARD" #elif defined(SEEEDUINO_ZERO) #define BOARD_TYPE "SAMD SEEEDUINO_ZERO" #elif defined(SEEEDUINO_LORAWAN) #define BOARD_TYPE "SAMD SEEEDUINO_LORAWAN" #elif defined(SEEED_GROVE_UI_WIRELESS) #define BOARD_TYPE "SAMD SEEED_GROVE_UI_WIRELESS" #elif defined(__SAMD21E18A__) #define BOARD_TYPE "SAMD21E18A" #elif defined(__SAMD21G18A__) #define BOARD_TYPE "SAMD21G18A" #elif defined(__SAMD51G19A__) #define BOARD_TYPE "SAMD51G19A" #elif defined(__SAMD51J19A__) #define BOARD_TYPE "SAMD51J19A" #elif defined(__SAMD51P19A__) #define BOARD_TYPE "__SAMD51P19A__" #elif defined(__SAMD51J20A__) #define BOARD_TYPE "SAMD51J20A" #elif defined(__SAM3X8E__) #define BOARD_TYPE "SAM3X8E" #elif defined(__CPU_ARC__) #define BOARD_TYPE "CPU_ARC" #elif defined(__SAMD51__) #define BOARD_TYPE "SAMD51" #else #define BOARD_TYPE "SAMD Unknown" #endif #endif #if ( defined(NRF52840_FEATHER) || defined(NRF52832_FEATHER) || defined(NRF52_SERIES) || defined(ARDUINO_NRF52_ADAFRUIT) || \ defined(NRF52840_FEATHER_SENSE) || defined(NRF52840_ITSYBITSY) || defined(NRF52840_CIRCUITPLAY) || defined(NRF52840_CLUE) || \ defined(NRF52840_METRO) || defined(NRF52840_PCA10056) || defined(PARTICLE_XENON) || defined(NINA_B302_ublox) || defined(NINA_B112_ublox) ) #if defined(WIFININA_USE_NRF52) #undef WIFININA_USE_NRF52 #endif #define WIFININA_USE_NRF52 true #endif #if defined(WIFININA_USE_NRF52) #if defined(NRF52840_FEATHER) #define BOARD_TYPE "NRF52840_FEATHER_EXPRESS" #elif defined(NRF52832_FEATHER) #define BOARD_TYPE "NRF52832_FEATHER" #elif defined(NRF52840_FEATHER_SENSE) #define BOARD_TYPE "NRF52840_FEATHER_SENSE" #elif defined(NRF52840_ITSYBITSY) #define BOARD_TYPE "NRF52840_ITSYBITSY_EXPRESS" #elif defined(NRF52840_CIRCUITPLAY) #define BOARD_TYPE "NRF52840_CIRCUIT_PLAYGROUND" #elif defined(NRF52840_CLUE) #define BOARD_TYPE "NRF52840_CLUE" #elif defined(NRF52840_METRO) #define BOARD_TYPE "NRF52840_METRO_EXPRESS" #elif defined(NRF52840_PCA10056) #define BOARD_TYPE "NORDIC_NRF52840DK" #elif defined(NINA_B302_ublox) #define BOARD_TYPE "NINA_B302_ublox" #elif defined(NINA_B112_ublox) #define BOARD_TYPE "NINA_B112_ublox" #elif defined(PARTICLE_XENON) #define BOARD_TYPE "PARTICLE_XENON" #elif defined(MDBT50Q_RX) #define BOARD_TYPE "RAYTAC_MDBT50Q_RX" #elif defined(ARDUINO_NRF52_ADAFRUIT) #define BOARD_TYPE "ARDUINO_NRF52_ADAFRUIT" #else #define BOARD_TYPE "nRF52 Unknown" #endif #endif #if ( defined(ARDUINO_SAM_DUE) || defined(__SAM3X8E__) ) #if defined(WIFININA_USE_SAMDUE) #undef WIFININA_USE_SAMDUE #endif #define WIFININA_USE_SAMDUE true #endif #if defined(WIFININA_USE_SAMDUE) // For SAM DUE #if defined(ARDUINO_SAM_DUE) #define BOARD_TYPE "SAM DUE" #elif defined(__SAM3X8E__) #define BOARD_TYPE "SAM SAM3X8E" #else #define BOARD_TYPE "SAM Unknown" #endif #endif #if ( defined(STM32F0) || defined(STM32F1) || defined(STM32F2) || defined(STM32F3) ||defined(STM32F4) || defined(STM32F7) || \ defined(STM32L0) || defined(STM32L1) || defined(STM32L4) || defined(STM32H7) ||defined(STM32G0) || defined(STM32G4) || \ defined(STM32WB) || defined(STM32MP1) ) #if defined(WIFININA_USE_STM32) #undef WIFININA_USE_STM32 #endif #define WIFININA_USE_STM32 true #endif #if defined(WIFININA_USE_STM32) #if defined(STM32F0) #warning STM32F0 board selected #define BOARD_TYPE "STM32F0" #elif defined(STM32F1) #warning STM32F1 board selected #define BOARD_TYPE "STM32F1" #elif defined(STM32F2) #warning STM32F2 board selected #define BOARD_TYPE "STM32F2" #elif defined(STM32F3) #warning STM32F3 board selected #define BOARD_TYPE "STM32F3" #elif defined(STM32F4) #warning STM32F4 board selected #define BOARD_TYPE "STM32F4" #elif defined(STM32F7) #warning STM32F7 board selected #define BOARD_TYPE "STM32F7" #elif defined(STM32L0) #warning STM32L0 board selected #define BOARD_TYPE "STM32L0" #elif defined(STM32L1) #warning STM32L1 board selected #define BOARD_TYPE "STM32L1" #elif defined(STM32L4) #warning STM32L4 board selected #define BOARD_TYPE "STM32L4" #elif defined(STM32H7) #warning STM32H7 board selected #define BOARD_TYPE "STM32H7" #elif defined(STM32G0) #warning STM32G0 board selected #define BOARD_TYPE "STM32G0" #elif defined(STM32G4) #warning STM32G4 board selected #define BOARD_TYPE "STM32G4" #elif defined(STM32WB) #warning STM32WB board selected #define BOARD_TYPE "STM32WB" #elif defined(STM32MP1) #warning STM32MP1 board selected #define BOARD_TYPE "STM32MP1" #else #warning STM32 unknown board selected #define BOARD_TYPE "STM32 Unknown" #endif #endif #ifdef CORE_TEENSY #if defined(WIFININA_USE_TEENSY) #undef WIFININA_USE_TEENSY #endif #define WIFININA_USE_TEENSY true #if defined(__IMXRT1062__) // For Teensy 4.1/4.0 #define BOARD_TYPE "TEENSY 4.1/4.0" #elif defined(__MK66FX1M0__) #define BOARD_TYPE "Teensy 3.6" #elif defined(__MK64FX512__) #define BOARD_TYPE "Teensy 3.5" #elif defined(__MKL26Z64__) #define BOARD_TYPE "Teensy LC" #elif defined(__MK20DX256__) #define BOARD_TYPE "Teensy 3.2" // and Teensy 3.1 (obsolete) #elif defined(__MK20DX128__) #define BOARD_TYPE "Teensy 3.0" #elif defined(__AVR_AT90USB1286__) #error Teensy 2.0++ not supported yet #elif defined(__AVR_ATmega32U4__) #error Teensy 2.0 not supported yet #else // For Other Boards #define BOARD_TYPE "Unknown Teensy Board" #endif #endif #if ( defined(ARDUINO_ARCH_RP2040) || defined(ARDUINO_RASPBERRY_PI_PICO) || defined(ARDUINO_ADAFRUIT_FEATHER_RP2040) || defined(ARDUINO_GENERIC_RP2040) ) #if defined(WIFININA_USE_RP2040) #undef WIFININA_USE_RP2040 #endif #define WIFININA_USE_RP2040 true #if defined(ARDUINO_ARCH_MBED) #if defined(BOARD_NAME) #undef BOARD_NAME #endif #if defined(ARDUINO_NANO_RP2040_CONNECT) #define BOARD_NAME "MBED NANO_RP2040_CONNECT" #elif defined(ARDUINO_RASPBERRY_PI_PICO) #define BOARD_NAME "MBED RASPBERRY_PI_PICO" #elif defined(ARDUINO_ADAFRUIT_FEATHER_RP2040) #define BOARD_NAME "MBED DAFRUIT_FEATHER_RP2040" #elif defined(ARDUINO_GENERIC_RP2040) #define BOARD_NAME "MBED GENERIC_RP2040" #else #define BOARD_NAME "MBED Unknown RP2040" #endif #endif #endif #if ( defined(__AVR_ATmega2560__) || defined(__AVR_ATmega2561__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega1281__) || \ defined(__AVR_ATmega640__) || defined(__AVR_ATmega641__)) #define BOARD_TYPE "Arduino AVR Mega2560/ADK" #warning Using Arduino AVR Mega, Mega640(P), Mega2560/ADK. #elif ( defined(__AVR_ATmega644__) || defined(__AVR_ATmega644A__) || defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644PA__) || \ defined(ARDUINO_AVR_UNO) || defined(ARDUINO_AVR_NANO) || defined(ARDUINO_AVR_MINI) || defined(ARDUINO_AVR_ETHERNET) || \ defined(ARDUINO_AVR_FIO) || defined(ARDUINO_AVR_BT) || defined(ARDUINO_AVR_LILYPAD) || defined(ARDUINO_AVR_PRO) || \ defined(ARDUINO_AVR_NG) || defined(ARDUINO_AVR_UNO_WIFI_DEV_ED) || defined(ARDUINO_AVR_DUEMILANOVE) ) #define BOARD_TYPE "Arduino AVR UNO, Nano, etc." #warning Using Aduino AVR ATMega644(P), ATMega328(P) such as UNO, Nano. #elif ( defined(ARDUINO_AVR_FEATHER328P) || defined(ARDUINO_AVR_METRO) || defined(ARDUINO_AVR_PROTRINKET5) || defined(ARDUINO_AVR_PROTRINKET3) || \ defined(ARDUINO_AVR_PROTRINKET5FTDI) || defined(ARDUINO_AVR_PROTRINKET3FTDI) ) #define BOARD_TYPE "Adafruit AVR ATMega328(P)" #warning Using Adafruit ATMega328(P), such as AVR_FEATHER328P or AVR_METRO. #elif ( defined(ARDUINO_AVR_LEONARDO) || defined(ARDUINO_AVR_LEONARDO_ETH) || defined(ARDUINO_AVR_YUN) || defined(ARDUINO_AVR_MICRO) || \ defined(ARDUINO_AVR_ESPLORA) || defined(ARDUINO_AVR_LILYPAD_USB) || defined(ARDUINO_AVR_ROBOT_CONTROL) || defined(ARDUINO_AVR_ROBOT_MOTOR) || \ defined(ARDUINO_AVR_CIRCUITPLAY) || defined(ARDUINO_AVR_YUNMINI) || defined(ARDUINO_AVR_INDUSTRIAL101) || defined(ARDUINO_AVR_LININO_ONE) ) #define BOARD_TYPE "Arduino AVR ATMega32U4" #warning Using Arduino ATMega32U4, such as Leonardo or Leonardo ETH. #elif ( defined(ARDUINO_AVR_FLORA8 ) || defined(ARDUINO_AVR_FEATHER32U4) || defined(ARDUINO_AVR_CIRCUITPLAY) || defined(ARDUINO_AVR_ITSYBITSY32U4_5V) || \ defined(ARDUINO_AVR_ITSYBITSY32U4_3V) || defined(ARDUINO_AVR_BLUEFRUITMICRO) || defined(ARDUINO_AVR_ADAFRUIT32U4) ) #define BOARD_TYPE "Adafruit AVR ATMega32U4" #warning Using Adafruit ATMega32U4, such as Feather_32u4, AVR_CIRCUITPLAY, etc. #elif ( defined(__AVR_ATmega32U4__) || defined(ARDUINO_AVR_MAKEYMAKEY ) || defined(ARDUINO_AVR_PROMICRO) || defined(ARDUINO_AVR_FIOV3) || \ defined(ARDUINO_AVR_QDUINOMINI) || defined(ARDUINO_AVR_LILYPAD_ARDUINO_USB_PLUS_BOARD ) ) #define BOARD_TYPE "Generic or Sparkfun AVR ATMega32U4" #warning Using Generic ATMega32U4, such as Sparkfun AVR_MAKEYMAKEY, AVR_PROMICRO, etc. #elif ( defined(__AVR_ATmega328P__) || defined(ARDUINO_AVR_DIGITAL_SANDBOX ) || defined(ARDUINO_REDBOT) || defined(ARDUINO_AVR_SERIAL_7_SEGMENT) ) #define BOARD_TYPE "Generic or Sparkfun AVR ATMega328P" #warning Using Generic ATMega328P, such as Sparkfun AVR_DIGITAL_SANDBOX, REDBOT, etc. #elif ( defined(__AVR_ATmega128RFA1__) || defined(ARDUINO_ATMEGA128RFA1_DEV_BOARD) ) #define BOARD_TYPE "Generic or Sparkfun AVR ATMega128RFA1" #warning Using Generic ATMega128RFA1, such as Sparkfun ATMEGA128RFA1_DEV_BOARD, etc. #elif ( defined(ARDUINO_AVR_GEMMA) || defined(ARDUINO_AVR_TRINKET3) || defined(ARDUINO_AVR_TRINKET5) ) #error These AVR boards are not supported! Please check your Tools->Board setting. #endif #if ( defined(__AVR_ATmega4809__) || defined(ARDUINO_AVR_UNO_WIFI_REV2) || defined(ARDUINO_AVR_NANO_EVERY) ) #if !defined(BOARD_NAME) #if (ARDUINO_AVR_UNO_WIFI_REV2) #define BOARD_NAME "megaAVR UNO WiFi Rev2" #elif (ARDUINO_AVR_NANO_EVERY) #define BOARD_NAME "megaAVR Nano Every" #else #define BOARD_NAME "megaAVR Unknown" #endif #endif #endif #ifndef BOARD_TYPE #define BOARD_TYPE "Unknown board" #endif #ifndef BOARD_NAME #define BOARD_NAME BOARD_TYPE #endif #define DEBUG_WIFININA_PORT Serial // Debug Level from 0 to 4 #define _WIFININA_LOGLEVEL_ 1 #define _WIFIMULTI_LOGLEVEL_ 2 #endif //defines_h
16,997
C++
.h
355
44.084507
154
0.703826
khoih-prog/WiFiNINA_Generic
36
12
0
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,535
defines.h
khoih-prog_WiFiNINA_Generic/examples/ConnectWithWPA2Enterprise/defines.h
/**************************************************************************************************************************** defines.h For boards with WiFiNINA module/shield. Based on and modified from WiFiNINA library https://www.arduino.cc/en/Reference/WiFiNINA to support nRF52, SAMD21/SAMD51, STM32F/L/H/G/WB/MP1, Teensy, etc. boards besides Nano-33 IoT, MKRWIFI1010, MKRVIDOR400, etc. Built by Khoi Hoang https://github.com/khoih-prog/WiFiNINA_Generic Licensed under MIT license Copyright (c) 2018 Arduino SA. All rights reserved. Copyright (c) 2011-2014 Arduino LLC. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA *****************************************************************************************************************************/ #ifndef defines_h #define defines_h #if ( defined(ARDUINO_SAMD_ZERO) || defined(ARDUINO_SAMD_MKR1000) || defined(ARDUINO_SAMD_MKRWIFI1010) \ || defined(ARDUINO_SAMD_NANO_33_IOT) || defined(ARDUINO_SAMD_MKRFox1200) || defined(ARDUINO_SAMD_MKRWAN1300) || defined(ARDUINO_SAMD_MKRWAN1310) \ || defined(ARDUINO_SAMD_MKRGSM1400) || defined(ARDUINO_SAMD_MKRNB1500) || defined(ARDUINO_SAMD_MKRVIDOR4000) \ || defined(ARDUINO_SAMD_CIRCUITPLAYGROUND_EXPRESS) || defined(__SAMD51__) || defined(__SAMD51J20A__) \ || defined(__SAMD51J19A__) || defined(__SAMD51G19A__) || defined(__SAMD51P19A__) \ || defined(__SAMD21E15A__) || defined(__SAMD21E16A__) || defined(__SAMD21E17A__) || defined(__SAMD21E18A__) \ || defined(__SAMD21G15A__) || defined(__SAMD21G16A__) || defined(__SAMD21G17A__) || defined(__SAMD21G18A__) \ || defined(__SAMD21J15A__) || defined(__SAMD21J16A__) || defined(__SAMD21J17A__) || defined(__SAMD21J18A__) ) #if defined(WIFININA_USE_SAMD) #undef WIFININA_USE_SAMD #endif #define WIFININA_USE_SAMD true #endif #if defined(WIFININA_USE_SAMD) #if defined(ARDUINO_SAMD_ZERO) #define BOARD_TYPE "SAMD Zero" #elif defined(ARDUINO_SAMD_MKR1000) #define BOARD_TYPE "SAMD MKR1000" #elif defined(ARDUINO_SAMD_MKRWIFI1010) #define BOARD_TYPE "SAMD MKRWIFI1010" #elif defined(ARDUINO_SAMD_NANO_33_IOT) #define BOARD_TYPE "SAMD NANO_33_IOT" #elif defined(ARDUINO_SAMD_MKRFox1200) #define BOARD_TYPE "SAMD MKRFox1200" #elif ( defined(ARDUINO_SAMD_MKRWAN1300) || defined(ARDUINO_SAMD_MKRWAN1310) ) #define BOARD_TYPE "SAMD MKRWAN13X0" #elif defined(ARDUINO_SAMD_MKRGSM1400) #define BOARD_TYPE "SAMD MKRGSM1400" #elif defined(ARDUINO_SAMD_MKRNB1500) #define BOARD_TYPE "SAMD MKRNB1500" #elif defined(ARDUINO_SAMD_MKRVIDOR4000) #define BOARD_TYPE "SAMD MKRVIDOR4000" #elif defined(ARDUINO_SAMD_CIRCUITPLAYGROUND_EXPRESS) #define BOARD_TYPE "SAMD ARDUINO_SAMD_CIRCUITPLAYGROUND_EXPRESS" #elif defined(ADAFRUIT_FEATHER_M0_EXPRESS) #define BOARD_TYPE "SAMD21 ADAFRUIT_FEATHER_M0_EXPRESS" #elif defined(ADAFRUIT_METRO_M0_EXPRESS) #define BOARD_TYPE "SAMD21 ADAFRUIT_METRO_M0_EXPRESS" #elif defined(ADAFRUIT_CIRCUITPLAYGROUND_M0) #define BOARD_TYPE "SAMD21 ADAFRUIT_CIRCUITPLAYGROUND_M0" #elif defined(ADAFRUIT_GEMMA_M0) #define BOARD_TYPE "SAMD21 ADAFRUIT_GEMMA_M0" #elif defined(ADAFRUIT_TRINKET_M0) #define BOARD_TYPE "SAMD21 ADAFRUIT_TRINKET_M0" #elif defined(ADAFRUIT_ITSYBITSY_M0) #define BOARD_TYPE "SAMD21 ADAFRUIT_ITSYBITSY_M0" #elif defined(ARDUINO_SAMD_HALLOWING_M0) #define BOARD_TYPE "SAMD21 ARDUINO_SAMD_HALLOWING_M0" #elif defined(ADAFRUIT_METRO_M4_EXPRESS) #define BOARD_TYPE "SAMD51 ADAFRUIT_METRO_M4_EXPRESS" #elif defined(ADAFRUIT_GRAND_CENTRAL_M4) #define BOARD_TYPE "SAMD51 ADAFRUIT_GRAND_CENTRAL_M4" #elif defined(ADAFRUIT_FEATHER_M4_EXPRESS) #define BOARD_TYPE "SAMD51 ADAFRUIT_FEATHER_M4_EXPRESS" #elif defined(ADAFRUIT_ITSYBITSY_M4_EXPRESS) #define BOARD_TYPE "SAMD51 ADAFRUIT_ITSYBITSY_M4_EXPRESS" #elif defined(ADAFRUIT_TRELLIS_M4_EXPRESS) #define BOARD_TYPE "SAMD51 ADAFRUIT_TRELLIS_M4_EXPRESS" #elif defined(ADAFRUIT_PYPORTAL) #define BOARD_TYPE "SAMD51 ADAFRUIT_PYPORTAL" #elif defined(ADAFRUIT_PYPORTAL_M4_TITANO) #define BOARD_TYPE "SAMD51 ADAFRUIT_PYPORTAL_M4_TITANO" #elif defined(ADAFRUIT_PYBADGE_M4_EXPRESS) #define BOARD_TYPE "SAMD51 ADAFRUIT_PYBADGE_M4_EXPRESS" #elif defined(ADAFRUIT_METRO_M4_AIRLIFT_LITE) #define BOARD_TYPE "SAMD51 ADAFRUIT_METRO_M4_AIRLIFT_LITE" #elif defined(ADAFRUIT_PYGAMER_M4_EXPRESS) #define BOARD_TYPE "SAMD51 ADAFRUIT_PYGAMER_M4_EXPRESS" #elif defined(ADAFRUIT_PYGAMER_ADVANCE_M4_EXPRESS) #define BOARD_TYPE "SAMD51 ADAFRUIT_PYGAMER_ADVANCE_M4_EXPRESS" #elif defined(ADAFRUIT_PYBADGE_AIRLIFT_M4) #define BOARD_TYPE "SAMD51 ADAFRUIT_PYBADGE_AIRLIFT_M4" #elif defined(ADAFRUIT_MONSTER_M4SK_EXPRESS) #define BOARD_TYPE "SAMD51 ADAFRUIT_MONSTER_M4SK_EXPRESS" #elif defined(ADAFRUIT_HALLOWING_M4_EXPRESS) #define BOARD_TYPE "SAMD51 ADAFRUIT_HALLOWING_M4_EXPRESS" #elif defined(SEEED_WIO_TERMINAL) #define BOARD_TYPE "SAMD SEEED_WIO_TERMINAL" #elif defined(SEEED_FEMTO_M0) #define BOARD_TYPE "SAMD SEEED_FEMTO_M0" #elif defined(SEEED_XIAO_M0) #define BOARD_TYPE "SAMD SEEED_XIAO_M0" #elif defined(Wio_Lite_MG126) #define BOARD_TYPE "SAMD SEEED Wio_Lite_MG126" #elif defined(WIO_GPS_BOARD) #define BOARD_TYPE "SAMD SEEED WIO_GPS_BOARD" #elif defined(SEEEDUINO_ZERO) #define BOARD_TYPE "SAMD SEEEDUINO_ZERO" #elif defined(SEEEDUINO_LORAWAN) #define BOARD_TYPE "SAMD SEEEDUINO_LORAWAN" #elif defined(SEEED_GROVE_UI_WIRELESS) #define BOARD_TYPE "SAMD SEEED_GROVE_UI_WIRELESS" #elif defined(__SAMD21E18A__) #define BOARD_TYPE "SAMD21E18A" #elif defined(__SAMD21G18A__) #define BOARD_TYPE "SAMD21G18A" #elif defined(__SAMD51G19A__) #define BOARD_TYPE "SAMD51G19A" #elif defined(__SAMD51J19A__) #define BOARD_TYPE "SAMD51J19A" #elif defined(__SAMD51P19A__) #define BOARD_TYPE "__SAMD51P19A__" #elif defined(__SAMD51J20A__) #define BOARD_TYPE "SAMD51J20A" #elif defined(__SAM3X8E__) #define BOARD_TYPE "SAM3X8E" #elif defined(__CPU_ARC__) #define BOARD_TYPE "CPU_ARC" #elif defined(__SAMD51__) #define BOARD_TYPE "SAMD51" #else #define BOARD_TYPE "SAMD Unknown" #endif #endif #if ( defined(NRF52840_FEATHER) || defined(NRF52832_FEATHER) || defined(NRF52_SERIES) || defined(ARDUINO_NRF52_ADAFRUIT) || \ defined(NRF52840_FEATHER_SENSE) || defined(NRF52840_ITSYBITSY) || defined(NRF52840_CIRCUITPLAY) || defined(NRF52840_CLUE) || \ defined(NRF52840_METRO) || defined(NRF52840_PCA10056) || defined(PARTICLE_XENON) || defined(NINA_B302_ublox) || defined(NINA_B112_ublox) ) #if defined(WIFININA_USE_NRF52) #undef WIFININA_USE_NRF52 #endif #define WIFININA_USE_NRF52 true #endif #if defined(WIFININA_USE_NRF52) #if defined(NRF52840_FEATHER) #define BOARD_TYPE "NRF52840_FEATHER_EXPRESS" #elif defined(NRF52832_FEATHER) #define BOARD_TYPE "NRF52832_FEATHER" #elif defined(NRF52840_FEATHER_SENSE) #define BOARD_TYPE "NRF52840_FEATHER_SENSE" #elif defined(NRF52840_ITSYBITSY) #define BOARD_TYPE "NRF52840_ITSYBITSY_EXPRESS" #elif defined(NRF52840_CIRCUITPLAY) #define BOARD_TYPE "NRF52840_CIRCUIT_PLAYGROUND" #elif defined(NRF52840_CLUE) #define BOARD_TYPE "NRF52840_CLUE" #elif defined(NRF52840_METRO) #define BOARD_TYPE "NRF52840_METRO_EXPRESS" #elif defined(NRF52840_PCA10056) #define BOARD_TYPE "NORDIC_NRF52840DK" #elif defined(NINA_B302_ublox) #define BOARD_TYPE "NINA_B302_ublox" #elif defined(NINA_B112_ublox) #define BOARD_TYPE "NINA_B112_ublox" #elif defined(PARTICLE_XENON) #define BOARD_TYPE "PARTICLE_XENON" #elif defined(MDBT50Q_RX) #define BOARD_TYPE "RAYTAC_MDBT50Q_RX" #elif defined(ARDUINO_NRF52_ADAFRUIT) #define BOARD_TYPE "ARDUINO_NRF52_ADAFRUIT" #else #define BOARD_TYPE "nRF52 Unknown" #endif #endif #if ( defined(ARDUINO_SAM_DUE) || defined(__SAM3X8E__) ) #if defined(WIFININA_USE_SAMDUE) #undef WIFININA_USE_SAMDUE #endif #define WIFININA_USE_SAMDUE true #endif #if defined(WIFININA_USE_SAMDUE) // For SAM DUE #if defined(ARDUINO_SAM_DUE) #define BOARD_TYPE "SAM DUE" #elif defined(__SAM3X8E__) #define BOARD_TYPE "SAM SAM3X8E" #else #define BOARD_TYPE "SAM Unknown" #endif #endif #if ( defined(STM32F0) || defined(STM32F1) || defined(STM32F2) || defined(STM32F3) ||defined(STM32F4) || defined(STM32F7) || \ defined(STM32L0) || defined(STM32L1) || defined(STM32L4) || defined(STM32H7) ||defined(STM32G0) || defined(STM32G4) || \ defined(STM32WB) || defined(STM32MP1) ) #if defined(WIFININA_USE_STM32) #undef WIFININA_USE_STM32 #endif #define WIFININA_USE_STM32 true #endif #if defined(WIFININA_USE_STM32) #if defined(STM32F0) #warning STM32F0 board selected #define BOARD_TYPE "STM32F0" #elif defined(STM32F1) #warning STM32F1 board selected #define BOARD_TYPE "STM32F1" #elif defined(STM32F2) #warning STM32F2 board selected #define BOARD_TYPE "STM32F2" #elif defined(STM32F3) #warning STM32F3 board selected #define BOARD_TYPE "STM32F3" #elif defined(STM32F4) #warning STM32F4 board selected #define BOARD_TYPE "STM32F4" #elif defined(STM32F7) #warning STM32F7 board selected #define BOARD_TYPE "STM32F7" #elif defined(STM32L0) #warning STM32L0 board selected #define BOARD_TYPE "STM32L0" #elif defined(STM32L1) #warning STM32L1 board selected #define BOARD_TYPE "STM32L1" #elif defined(STM32L4) #warning STM32L4 board selected #define BOARD_TYPE "STM32L4" #elif defined(STM32H7) #warning STM32H7 board selected #define BOARD_TYPE "STM32H7" #elif defined(STM32G0) #warning STM32G0 board selected #define BOARD_TYPE "STM32G0" #elif defined(STM32G4) #warning STM32G4 board selected #define BOARD_TYPE "STM32G4" #elif defined(STM32WB) #warning STM32WB board selected #define BOARD_TYPE "STM32WB" #elif defined(STM32MP1) #warning STM32MP1 board selected #define BOARD_TYPE "STM32MP1" #else #warning STM32 unknown board selected #define BOARD_TYPE "STM32 Unknown" #endif #endif #ifdef CORE_TEENSY #if defined(WIFININA_USE_TEENSY) #undef WIFININA_USE_TEENSY #endif #define WIFININA_USE_TEENSY true #if defined(__IMXRT1062__) // For Teensy 4.1/4.0 #define BOARD_TYPE "TEENSY 4.1/4.0" #elif defined(__MK66FX1M0__) #define BOARD_TYPE "Teensy 3.6" #elif defined(__MK64FX512__) #define BOARD_TYPE "Teensy 3.5" #elif defined(__MKL26Z64__) #define BOARD_TYPE "Teensy LC" #elif defined(__MK20DX256__) #define BOARD_TYPE "Teensy 3.2" // and Teensy 3.1 (obsolete) #elif defined(__MK20DX128__) #define BOARD_TYPE "Teensy 3.0" #elif defined(__AVR_AT90USB1286__) #error Teensy 2.0++ not supported yet #elif defined(__AVR_ATmega32U4__) #error Teensy 2.0 not supported yet #else // For Other Boards #define BOARD_TYPE "Unknown Teensy Board" #endif #endif #if ( defined(ARDUINO_ARCH_RP2040) || defined(ARDUINO_RASPBERRY_PI_PICO) || defined(ARDUINO_ADAFRUIT_FEATHER_RP2040) || defined(ARDUINO_GENERIC_RP2040) ) #if defined(WIFININA_USE_RP2040) #undef WIFININA_USE_RP2040 #endif #define WIFININA_USE_RP2040 true #if defined(ARDUINO_ARCH_MBED) #if defined(BOARD_NAME) #undef BOARD_NAME #endif #if defined(ARDUINO_NANO_RP2040_CONNECT) #define BOARD_NAME "MBED NANO_RP2040_CONNECT" #elif defined(ARDUINO_RASPBERRY_PI_PICO) #define BOARD_NAME "MBED RASPBERRY_PI_PICO" #elif defined(ARDUINO_ADAFRUIT_FEATHER_RP2040) #define BOARD_NAME "MBED DAFRUIT_FEATHER_RP2040" #elif defined(ARDUINO_GENERIC_RP2040) #define BOARD_NAME "MBED GENERIC_RP2040" #else #define BOARD_NAME "MBED Unknown RP2040" #endif #endif #endif #if ( defined(__AVR_ATmega2560__) || defined(__AVR_ATmega2561__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega1281__) || \ defined(__AVR_ATmega640__) || defined(__AVR_ATmega641__)) #define BOARD_TYPE "Arduino AVR Mega2560/ADK" #warning Using Arduino AVR Mega, Mega640(P), Mega2560/ADK. #elif ( defined(__AVR_ATmega644__) || defined(__AVR_ATmega644A__) || defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644PA__) || \ defined(ARDUINO_AVR_UNO) || defined(ARDUINO_AVR_NANO) || defined(ARDUINO_AVR_MINI) || defined(ARDUINO_AVR_ETHERNET) || \ defined(ARDUINO_AVR_FIO) || defined(ARDUINO_AVR_BT) || defined(ARDUINO_AVR_LILYPAD) || defined(ARDUINO_AVR_PRO) || \ defined(ARDUINO_AVR_NG) || defined(ARDUINO_AVR_UNO_WIFI_DEV_ED) || defined(ARDUINO_AVR_DUEMILANOVE) ) #define BOARD_TYPE "Arduino AVR UNO, Nano, etc." #warning Using Aduino AVR ATMega644(P), ATMega328(P) such as UNO, Nano. #elif ( defined(ARDUINO_AVR_FEATHER328P) || defined(ARDUINO_AVR_METRO) || defined(ARDUINO_AVR_PROTRINKET5) || defined(ARDUINO_AVR_PROTRINKET3) || \ defined(ARDUINO_AVR_PROTRINKET5FTDI) || defined(ARDUINO_AVR_PROTRINKET3FTDI) ) #define BOARD_TYPE "Adafruit AVR ATMega328(P)" #warning Using Adafruit ATMega328(P), such as AVR_FEATHER328P or AVR_METRO. #elif ( defined(ARDUINO_AVR_LEONARDO) || defined(ARDUINO_AVR_LEONARDO_ETH) || defined(ARDUINO_AVR_YUN) || defined(ARDUINO_AVR_MICRO) || \ defined(ARDUINO_AVR_ESPLORA) || defined(ARDUINO_AVR_LILYPAD_USB) || defined(ARDUINO_AVR_ROBOT_CONTROL) || defined(ARDUINO_AVR_ROBOT_MOTOR) || \ defined(ARDUINO_AVR_CIRCUITPLAY) || defined(ARDUINO_AVR_YUNMINI) || defined(ARDUINO_AVR_INDUSTRIAL101) || defined(ARDUINO_AVR_LININO_ONE) ) #define BOARD_TYPE "Arduino AVR ATMega32U4" #warning Using Arduino ATMega32U4, such as Leonardo or Leonardo ETH. #elif ( defined(ARDUINO_AVR_FLORA8 ) || defined(ARDUINO_AVR_FEATHER32U4) || defined(ARDUINO_AVR_CIRCUITPLAY) || defined(ARDUINO_AVR_ITSYBITSY32U4_5V) || \ defined(ARDUINO_AVR_ITSYBITSY32U4_3V) || defined(ARDUINO_AVR_BLUEFRUITMICRO) || defined(ARDUINO_AVR_ADAFRUIT32U4) ) #define BOARD_TYPE "Adafruit AVR ATMega32U4" #warning Using Adafruit ATMega32U4, such as Feather_32u4, AVR_CIRCUITPLAY, etc. #elif ( defined(__AVR_ATmega32U4__) || defined(ARDUINO_AVR_MAKEYMAKEY ) || defined(ARDUINO_AVR_PROMICRO) || defined(ARDUINO_AVR_FIOV3) || \ defined(ARDUINO_AVR_QDUINOMINI) || defined(ARDUINO_AVR_LILYPAD_ARDUINO_USB_PLUS_BOARD ) ) #define BOARD_TYPE "Generic or Sparkfun AVR ATMega32U4" #warning Using Generic ATMega32U4, such as Sparkfun AVR_MAKEYMAKEY, AVR_PROMICRO, etc. #elif ( defined(__AVR_ATmega328P__) || defined(ARDUINO_AVR_DIGITAL_SANDBOX ) || defined(ARDUINO_REDBOT) || defined(ARDUINO_AVR_SERIAL_7_SEGMENT) ) #define BOARD_TYPE "Generic or Sparkfun AVR ATMega328P" #warning Using Generic ATMega328P, such as Sparkfun AVR_DIGITAL_SANDBOX, REDBOT, etc. #elif ( defined(__AVR_ATmega128RFA1__) || defined(ARDUINO_ATMEGA128RFA1_DEV_BOARD) ) #define BOARD_TYPE "Generic or Sparkfun AVR ATMega128RFA1" #warning Using Generic ATMega128RFA1, such as Sparkfun ATMEGA128RFA1_DEV_BOARD, etc. #elif ( defined(ARDUINO_AVR_GEMMA) || defined(ARDUINO_AVR_TRINKET3) || defined(ARDUINO_AVR_TRINKET5) ) #error These AVR boards are not supported! Please check your Tools->Board setting. #endif #if ( defined(__AVR_ATmega4809__) || defined(ARDUINO_AVR_UNO_WIFI_REV2) || defined(ARDUINO_AVR_NANO_EVERY) ) #if !defined(BOARD_NAME) #if (ARDUINO_AVR_UNO_WIFI_REV2) #define BOARD_NAME "megaAVR UNO WiFi Rev2" #elif (ARDUINO_AVR_NANO_EVERY) #define BOARD_NAME "megaAVR Nano Every" #else #define BOARD_NAME "megaAVR Unknown" #endif #endif #endif #ifndef BOARD_TYPE #define BOARD_TYPE "Unknown board" #endif #ifndef BOARD_NAME #define BOARD_NAME BOARD_TYPE #endif #define DEBUG_WIFININA_PORT Serial // Debug Level from 0 to 4 #define _WIFININA_LOGLEVEL_ 1 #endif //defines_h
16,962
C++
.h
354
44.115819
154
0.70378
khoih-prog/WiFiNINA_Generic
36
12
0
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,536
defines.h
khoih-prog_WiFiNINA_Generic/examples/ConnectNoEncryption/defines.h
/**************************************************************************************************************************** defines.h For boards with WiFiNINA module/shield. Based on and modified from WiFiNINA library https://www.arduino.cc/en/Reference/WiFiNINA to support nRF52, SAMD21/SAMD51, STM32F/L/H/G/WB/MP1, Teensy, etc. boards besides Nano-33 IoT, MKRWIFI1010, MKRVIDOR400, etc. Built by Khoi Hoang https://github.com/khoih-prog/WiFiNINA_Generic Licensed under MIT license Copyright (c) 2018 Arduino SA. All rights reserved. Copyright (c) 2011-2014 Arduino LLC. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA *****************************************************************************************************************************/ #ifndef defines_h #define defines_h #if ( defined(ARDUINO_SAMD_ZERO) || defined(ARDUINO_SAMD_MKR1000) || defined(ARDUINO_SAMD_MKRWIFI1010) \ || defined(ARDUINO_SAMD_NANO_33_IOT) || defined(ARDUINO_SAMD_MKRFox1200) || defined(ARDUINO_SAMD_MKRWAN1300) || defined(ARDUINO_SAMD_MKRWAN1310) \ || defined(ARDUINO_SAMD_MKRGSM1400) || defined(ARDUINO_SAMD_MKRNB1500) || defined(ARDUINO_SAMD_MKRVIDOR4000) \ || defined(ARDUINO_SAMD_CIRCUITPLAYGROUND_EXPRESS) || defined(__SAMD51__) || defined(__SAMD51J20A__) \ || defined(__SAMD51J19A__) || defined(__SAMD51G19A__) || defined(__SAMD51P19A__) \ || defined(__SAMD21E15A__) || defined(__SAMD21E16A__) || defined(__SAMD21E17A__) || defined(__SAMD21E18A__) \ || defined(__SAMD21G15A__) || defined(__SAMD21G16A__) || defined(__SAMD21G17A__) || defined(__SAMD21G18A__) \ || defined(__SAMD21J15A__) || defined(__SAMD21J16A__) || defined(__SAMD21J17A__) || defined(__SAMD21J18A__) ) #if defined(WIFININA_USE_SAMD) #undef WIFININA_USE_SAMD #endif #define WIFININA_USE_SAMD true #endif #if defined(WIFININA_USE_SAMD) #if defined(ARDUINO_SAMD_ZERO) #define BOARD_TYPE "SAMD Zero" #elif defined(ARDUINO_SAMD_MKR1000) #define BOARD_TYPE "SAMD MKR1000" #define USING_WIFI101 true #elif defined(ARDUINO_SAMD_MKRWIFI1010) #define BOARD_TYPE "SAMD MKRWIFI1010" #define USING_WIFI101 true #elif defined(ARDUINO_SAMD_NANO_33_IOT) #define BOARD_TYPE "SAMD NANO_33_IOT" #elif defined(ARDUINO_SAMD_MKRFox1200) #define BOARD_TYPE "SAMD MKRFox1200" #elif ( defined(ARDUINO_SAMD_MKRWAN1300) || defined(ARDUINO_SAMD_MKRWAN1310) ) #define BOARD_TYPE "SAMD MKRWAN13X0" #elif defined(ARDUINO_SAMD_MKRGSM1400) #define BOARD_TYPE "SAMD MKRGSM1400" #elif defined(ARDUINO_SAMD_MKRNB1500) #define BOARD_TYPE "SAMD MKRNB1500" #elif defined(ARDUINO_SAMD_MKRVIDOR4000) #define BOARD_TYPE "SAMD MKRVIDOR4000" #elif defined(ARDUINO_SAMD_CIRCUITPLAYGROUND_EXPRESS) #define BOARD_TYPE "SAMD ARDUINO_SAMD_CIRCUITPLAYGROUND_EXPRESS" #elif defined(ADAFRUIT_FEATHER_M0_EXPRESS) #define BOARD_TYPE "SAMD21 ADAFRUIT_FEATHER_M0_EXPRESS" #elif defined(ADAFRUIT_METRO_M0_EXPRESS) #define BOARD_TYPE "SAMD21 ADAFRUIT_METRO_M0_EXPRESS" #elif defined(ADAFRUIT_CIRCUITPLAYGROUND_M0) #define BOARD_TYPE "SAMD21 ADAFRUIT_CIRCUITPLAYGROUND_M0" #elif defined(ADAFRUIT_GEMMA_M0) #define BOARD_TYPE "SAMD21 ADAFRUIT_GEMMA_M0" #elif defined(ADAFRUIT_TRINKET_M0) #define BOARD_TYPE "SAMD21 ADAFRUIT_TRINKET_M0" #elif defined(ADAFRUIT_ITSYBITSY_M0) #define BOARD_TYPE "SAMD21 ADAFRUIT_ITSYBITSY_M0" #elif defined(ARDUINO_SAMD_HALLOWING_M0) #define BOARD_TYPE "SAMD21 ARDUINO_SAMD_HALLOWING_M0" #elif defined(ADAFRUIT_METRO_M4_EXPRESS) #define BOARD_TYPE "SAMD51 ADAFRUIT_METRO_M4_EXPRESS" #elif defined(ADAFRUIT_GRAND_CENTRAL_M4) #define BOARD_TYPE "SAMD51 ADAFRUIT_GRAND_CENTRAL_M4" #elif defined(ADAFRUIT_FEATHER_M4_EXPRESS) #define BOARD_TYPE "SAMD51 ADAFRUIT_FEATHER_M4_EXPRESS" #elif defined(ADAFRUIT_ITSYBITSY_M4_EXPRESS) #define BOARD_TYPE "SAMD51 ADAFRUIT_ITSYBITSY_M4_EXPRESS" #elif defined(ADAFRUIT_TRELLIS_M4_EXPRESS) #define BOARD_TYPE "SAMD51 ADAFRUIT_TRELLIS_M4_EXPRESS" #elif defined(ADAFRUIT_PYPORTAL) #define BOARD_TYPE "SAMD51 ADAFRUIT_PYPORTAL" #elif defined(ADAFRUIT_PYPORTAL_M4_TITANO) #define BOARD_TYPE "SAMD51 ADAFRUIT_PYPORTAL_M4_TITANO" #elif defined(ADAFRUIT_PYBADGE_M4_EXPRESS) #define BOARD_TYPE "SAMD51 ADAFRUIT_PYBADGE_M4_EXPRESS" #elif defined(ADAFRUIT_METRO_M4_AIRLIFT_LITE) #define BOARD_TYPE "SAMD51 ADAFRUIT_METRO_M4_AIRLIFT_LITE" #elif defined(ADAFRUIT_PYGAMER_M4_EXPRESS) #define BOARD_TYPE "SAMD51 ADAFRUIT_PYGAMER_M4_EXPRESS" #elif defined(ADAFRUIT_PYGAMER_ADVANCE_M4_EXPRESS) #define BOARD_TYPE "SAMD51 ADAFRUIT_PYGAMER_ADVANCE_M4_EXPRESS" #elif defined(ADAFRUIT_PYBADGE_AIRLIFT_M4) #define BOARD_TYPE "SAMD51 ADAFRUIT_PYBADGE_AIRLIFT_M4" #elif defined(ADAFRUIT_MONSTER_M4SK_EXPRESS) #define BOARD_TYPE "SAMD51 ADAFRUIT_MONSTER_M4SK_EXPRESS" #elif defined(ADAFRUIT_HALLOWING_M4_EXPRESS) #define BOARD_TYPE "SAMD51 ADAFRUIT_HALLOWING_M4_EXPRESS" #elif defined(SEEED_WIO_TERMINAL) #define BOARD_TYPE "SAMD SEEED_WIO_TERMINAL" #elif defined(SEEED_FEMTO_M0) #define BOARD_TYPE "SAMD SEEED_FEMTO_M0" #elif defined(SEEED_XIAO_M0) #define BOARD_TYPE "SAMD SEEED_XIAO_M0" #elif defined(Wio_Lite_MG126) #define BOARD_TYPE "SAMD SEEED Wio_Lite_MG126" #elif defined(WIO_GPS_BOARD) #define BOARD_TYPE "SAMD SEEED WIO_GPS_BOARD" #elif defined(SEEEDUINO_ZERO) #define BOARD_TYPE "SAMD SEEEDUINO_ZERO" #elif defined(SEEEDUINO_LORAWAN) #define BOARD_TYPE "SAMD SEEEDUINO_LORAWAN" #elif defined(SEEED_GROVE_UI_WIRELESS) #define BOARD_TYPE "SAMD SEEED_GROVE_UI_WIRELESS" #elif defined(__SAMD21E18A__) #define BOARD_TYPE "SAMD21E18A" #elif defined(__SAMD21G18A__) #define BOARD_TYPE "SAMD21G18A" #elif defined(__SAMD51G19A__) #define BOARD_TYPE "SAMD51G19A" #elif defined(__SAMD51J19A__) #define BOARD_TYPE "SAMD51J19A" #elif defined(__SAMD51P19A__) #define BOARD_TYPE "__SAMD51P19A__" #elif defined(__SAMD51J20A__) #define BOARD_TYPE "SAMD51J20A" #elif defined(__SAM3X8E__) #define BOARD_TYPE "SAM3X8E" #elif defined(__CPU_ARC__) #define BOARD_TYPE "CPU_ARC" #elif defined(__SAMD51__) #define BOARD_TYPE "SAMD51" #else #define BOARD_TYPE "SAMD Unknown" #endif #endif #if ( defined(NRF52840_FEATHER) || defined(NRF52832_FEATHER) || defined(NRF52_SERIES) || defined(ARDUINO_NRF52_ADAFRUIT) || \ defined(NRF52840_FEATHER_SENSE) || defined(NRF52840_ITSYBITSY) || defined(NRF52840_CIRCUITPLAY) || defined(NRF52840_CLUE) || \ defined(NRF52840_METRO) || defined(NRF52840_PCA10056) || defined(PARTICLE_XENON) || defined(NINA_B302_ublox) || defined(NINA_B112_ublox) ) #if defined(WIFININA_USE_NRF52) #undef WIFININA_USE_NRF52 #endif #define WIFININA_USE_NRF52 true #endif #if defined(WIFININA_USE_NRF52) #if defined(NRF52840_FEATHER) #define BOARD_TYPE "NRF52840_FEATHER_EXPRESS" #elif defined(NRF52832_FEATHER) #define BOARD_TYPE "NRF52832_FEATHER" #elif defined(NRF52840_FEATHER_SENSE) #define BOARD_TYPE "NRF52840_FEATHER_SENSE" #elif defined(NRF52840_ITSYBITSY) #define BOARD_TYPE "NRF52840_ITSYBITSY_EXPRESS" #elif defined(NRF52840_CIRCUITPLAY) #define BOARD_TYPE "NRF52840_CIRCUIT_PLAYGROUND" #elif defined(NRF52840_CLUE) #define BOARD_TYPE "NRF52840_CLUE" #elif defined(NRF52840_METRO) #define BOARD_TYPE "NRF52840_METRO_EXPRESS" #elif defined(NRF52840_PCA10056) #define BOARD_TYPE "NORDIC_NRF52840DK" #elif defined(NINA_B302_ublox) #define BOARD_TYPE "NINA_B302_ublox" #elif defined(NINA_B112_ublox) #define BOARD_TYPE "NINA_B112_ublox" #elif defined(PARTICLE_XENON) #define BOARD_TYPE "PARTICLE_XENON" #elif defined(MDBT50Q_RX) #define BOARD_TYPE "RAYTAC_MDBT50Q_RX" #elif defined(ARDUINO_NRF52_ADAFRUIT) #define BOARD_TYPE "ARDUINO_NRF52_ADAFRUIT" #else #define BOARD_TYPE "nRF52 Unknown" #endif #endif #if ( defined(ARDUINO_SAM_DUE) || defined(__SAM3X8E__) ) #if defined(WIFININA_USE_SAMDUE) #undef WIFININA_USE_SAMDUE #endif #define WIFININA_USE_SAMDUE true #endif #if defined(WIFININA_USE_SAMDUE) // For SAM DUE #if defined(ARDUINO_SAM_DUE) #define BOARD_TYPE "SAM DUE" #elif defined(__SAM3X8E__) #define BOARD_TYPE "SAM SAM3X8E" #else #define BOARD_TYPE "SAM Unknown" #endif #endif #if ( defined(STM32F0) || defined(STM32F1) || defined(STM32F2) || defined(STM32F3) ||defined(STM32F4) || defined(STM32F7) || \ defined(STM32L0) || defined(STM32L1) || defined(STM32L4) || defined(STM32H7) ||defined(STM32G0) || defined(STM32G4) || \ defined(STM32WB) || defined(STM32MP1) ) #if defined(WIFININA_USE_STM32) #undef WIFININA_USE_STM32 #endif #define WIFININA_USE_STM32 true #endif #if defined(WIFININA_USE_STM32) #if defined(STM32F0) #warning STM32F0 board selected #define BOARD_TYPE "STM32F0" #elif defined(STM32F1) #warning STM32F1 board selected #define BOARD_TYPE "STM32F1" #elif defined(STM32F2) #warning STM32F2 board selected #define BOARD_TYPE "STM32F2" #elif defined(STM32F3) #warning STM32F3 board selected #define BOARD_TYPE "STM32F3" #elif defined(STM32F4) #warning STM32F4 board selected #define BOARD_TYPE "STM32F4" #elif defined(STM32F7) #warning STM32F7 board selected #define BOARD_TYPE "STM32F7" #elif defined(STM32L0) #warning STM32L0 board selected #define BOARD_TYPE "STM32L0" #elif defined(STM32L1) #warning STM32L1 board selected #define BOARD_TYPE "STM32L1" #elif defined(STM32L4) #warning STM32L4 board selected #define BOARD_TYPE "STM32L4" #elif defined(STM32H7) #warning STM32H7 board selected #define BOARD_TYPE "STM32H7" #elif defined(STM32G0) #warning STM32G0 board selected #define BOARD_TYPE "STM32G0" #elif defined(STM32G4) #warning STM32G4 board selected #define BOARD_TYPE "STM32G4" #elif defined(STM32WB) #warning STM32WB board selected #define BOARD_TYPE "STM32WB" #elif defined(STM32MP1) #warning STM32MP1 board selected #define BOARD_TYPE "STM32MP1" #else #warning STM32 unknown board selected #define BOARD_TYPE "STM32 Unknown" #endif #endif #ifdef CORE_TEENSY #if defined(WIFININA_USE_TEENSY) #undef WIFININA_USE_TEENSY #endif #define WIFININA_USE_TEENSY true #if defined(__IMXRT1062__) // For Teensy 4.1/4.0 #define BOARD_TYPE "TEENSY 4.1/4.0" #elif defined(__MK66FX1M0__) #define BOARD_TYPE "Teensy 3.6" #elif defined(__MK64FX512__) #define BOARD_TYPE "Teensy 3.5" #elif defined(__MKL26Z64__) #define BOARD_TYPE "Teensy LC" #elif defined(__MK20DX256__) #define BOARD_TYPE "Teensy 3.2" // and Teensy 3.1 (obsolete) #elif defined(__MK20DX128__) #define BOARD_TYPE "Teensy 3.0" #elif defined(__AVR_AT90USB1286__) #error Teensy 2.0++ not supported yet #elif defined(__AVR_ATmega32U4__) #error Teensy 2.0 not supported yet #else // For Other Boards #define BOARD_TYPE "Unknown Teensy Board" #endif #endif #if ( defined(ARDUINO_ARCH_RP2040) || defined(ARDUINO_RASPBERRY_PI_PICO) || defined(ARDUINO_ADAFRUIT_FEATHER_RP2040) || defined(ARDUINO_GENERIC_RP2040) ) #if defined(WIFININA_USE_RP2040) #undef WIFININA_USE_RP2040 #endif #define WIFININA_USE_RP2040 true #if defined(ARDUINO_ARCH_MBED) #if defined(BOARD_NAME) #undef BOARD_NAME #endif #if defined(ARDUINO_NANO_RP2040_CONNECT) #define BOARD_NAME "MBED NANO_RP2040_CONNECT" #elif defined(ARDUINO_RASPBERRY_PI_PICO) #define BOARD_NAME "MBED RASPBERRY_PI_PICO" #elif defined(ARDUINO_ADAFRUIT_FEATHER_RP2040) #define BOARD_NAME "MBED DAFRUIT_FEATHER_RP2040" #elif defined(ARDUINO_GENERIC_RP2040) #define BOARD_NAME "MBED GENERIC_RP2040" #else #define BOARD_NAME "MBED Unknown RP2040" #endif #endif #endif #if ( defined(__AVR_ATmega2560__) || defined(__AVR_ATmega2561__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega1281__) || \ defined(__AVR_ATmega640__) || defined(__AVR_ATmega641__)) #define BOARD_TYPE "Arduino AVR Mega2560/ADK" #warning Using Arduino AVR Mega, Mega640(P), Mega2560/ADK. #elif ( defined(__AVR_ATmega644__) || defined(__AVR_ATmega644A__) || defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644PA__) || \ defined(ARDUINO_AVR_UNO) || defined(ARDUINO_AVR_NANO) || defined(ARDUINO_AVR_MINI) || defined(ARDUINO_AVR_ETHERNET) || \ defined(ARDUINO_AVR_FIO) || defined(ARDUINO_AVR_BT) || defined(ARDUINO_AVR_LILYPAD) || defined(ARDUINO_AVR_PRO) || \ defined(ARDUINO_AVR_NG) || defined(ARDUINO_AVR_UNO_WIFI_DEV_ED) || defined(ARDUINO_AVR_DUEMILANOVE) ) #define BOARD_TYPE "Arduino AVR UNO, Nano, etc." #warning Using Aduino AVR ATMega644(P), ATMega328(P) such as UNO, Nano. #elif ( defined(ARDUINO_AVR_FEATHER328P) || defined(ARDUINO_AVR_METRO) || defined(ARDUINO_AVR_PROTRINKET5) || defined(ARDUINO_AVR_PROTRINKET3) || \ defined(ARDUINO_AVR_PROTRINKET5FTDI) || defined(ARDUINO_AVR_PROTRINKET3FTDI) ) #define BOARD_TYPE "Adafruit AVR ATMega328(P)" #warning Using Adafruit ATMega328(P), such as AVR_FEATHER328P or AVR_METRO. #elif ( defined(ARDUINO_AVR_LEONARDO) || defined(ARDUINO_AVR_LEONARDO_ETH) || defined(ARDUINO_AVR_YUN) || defined(ARDUINO_AVR_MICRO) || \ defined(ARDUINO_AVR_ESPLORA) || defined(ARDUINO_AVR_LILYPAD_USB) || defined(ARDUINO_AVR_ROBOT_CONTROL) || defined(ARDUINO_AVR_ROBOT_MOTOR) || \ defined(ARDUINO_AVR_CIRCUITPLAY) || defined(ARDUINO_AVR_YUNMINI) || defined(ARDUINO_AVR_INDUSTRIAL101) || defined(ARDUINO_AVR_LININO_ONE) ) #define BOARD_TYPE "Arduino AVR ATMega32U4" #warning Using Arduino ATMega32U4, such as Leonardo or Leonardo ETH. #elif ( defined(ARDUINO_AVR_FLORA8 ) || defined(ARDUINO_AVR_FEATHER32U4) || defined(ARDUINO_AVR_CIRCUITPLAY) || defined(ARDUINO_AVR_ITSYBITSY32U4_5V) || \ defined(ARDUINO_AVR_ITSYBITSY32U4_3V) || defined(ARDUINO_AVR_BLUEFRUITMICRO) || defined(ARDUINO_AVR_ADAFRUIT32U4) ) #define BOARD_TYPE "Adafruit AVR ATMega32U4" #warning Using Adafruit ATMega32U4, such as Feather_32u4, AVR_CIRCUITPLAY, etc. #elif ( defined(__AVR_ATmega32U4__) || defined(ARDUINO_AVR_MAKEYMAKEY ) || defined(ARDUINO_AVR_PROMICRO) || defined(ARDUINO_AVR_FIOV3) || \ defined(ARDUINO_AVR_QDUINOMINI) || defined(ARDUINO_AVR_LILYPAD_ARDUINO_USB_PLUS_BOARD ) ) #define BOARD_TYPE "Generic or Sparkfun AVR ATMega32U4" #warning Using Generic ATMega32U4, such as Sparkfun AVR_MAKEYMAKEY, AVR_PROMICRO, etc. #elif ( defined(__AVR_ATmega328P__) || defined(ARDUINO_AVR_DIGITAL_SANDBOX ) || defined(ARDUINO_REDBOT) || defined(ARDUINO_AVR_SERIAL_7_SEGMENT) ) #define BOARD_TYPE "Generic or Sparkfun AVR ATMega328P" #warning Using Generic ATMega328P, such as Sparkfun AVR_DIGITAL_SANDBOX, REDBOT, etc. #elif ( defined(__AVR_ATmega128RFA1__) || defined(ARDUINO_ATMEGA128RFA1_DEV_BOARD) ) #define BOARD_TYPE "Generic or Sparkfun AVR ATMega128RFA1" #warning Using Generic ATMega128RFA1, such as Sparkfun ATMEGA128RFA1_DEV_BOARD, etc. #elif ( defined(ARDUINO_AVR_GEMMA) || defined(ARDUINO_AVR_TRINKET3) || defined(ARDUINO_AVR_TRINKET5) ) #error These AVR boards are not supported! Please check your Tools->Board setting. #endif #if ( defined(__AVR_ATmega4809__) || defined(ARDUINO_AVR_UNO_WIFI_REV2) || defined(ARDUINO_AVR_NANO_EVERY) ) #if !defined(BOARD_NAME) #if (ARDUINO_AVR_UNO_WIFI_REV2) #define BOARD_NAME "megaAVR UNO WiFi Rev2" #elif (ARDUINO_AVR_NANO_EVERY) #define BOARD_NAME "megaAVR Nano Every" #else #define BOARD_NAME "megaAVR Unknown" #endif #endif #endif #ifndef BOARD_TYPE #define BOARD_TYPE "Unknown board" #endif #ifndef BOARD_NAME #define BOARD_NAME BOARD_TYPE #endif #define DEBUG_WIFININA_PORT Serial // Debug Level from 0 to 4 #define _WIFININA_LOGLEVEL_ 1 #endif //defines_h
17,032
C++
.h
356
44.036517
154
0.703548
khoih-prog/WiFiNINA_Generic
36
12
0
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,537
defines.h
khoih-prog_WiFiNINA_Generic/examples/WiFiWebClient/defines.h
/**************************************************************************************************************************** defines.h For boards with WiFiNINA module/shield. Based on and modified from WiFiNINA library https://www.arduino.cc/en/Reference/WiFiNINA to support nRF52, SAMD21/SAMD51, STM32F/L/H/G/WB/MP1, Teensy, etc. boards besides Nano-33 IoT, MKRWIFI1010, MKRVIDOR400, etc. Built by Khoi Hoang https://github.com/khoih-prog/WiFiNINA_Generic Licensed under MIT license Copyright (c) 2018 Arduino SA. All rights reserved. Copyright (c) 2011-2014 Arduino LLC. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA *****************************************************************************************************************************/ #ifndef defines_h #define defines_h #if ( defined(ARDUINO_SAMD_ZERO) || defined(ARDUINO_SAMD_MKR1000) || defined(ARDUINO_SAMD_MKRWIFI1010) \ || defined(ARDUINO_SAMD_NANO_33_IOT) || defined(ARDUINO_SAMD_MKRFox1200) || defined(ARDUINO_SAMD_MKRWAN1300) || defined(ARDUINO_SAMD_MKRWAN1310) \ || defined(ARDUINO_SAMD_MKRGSM1400) || defined(ARDUINO_SAMD_MKRNB1500) || defined(ARDUINO_SAMD_MKRVIDOR4000) \ || defined(ARDUINO_SAMD_CIRCUITPLAYGROUND_EXPRESS) || defined(__SAMD51__) || defined(__SAMD51J20A__) \ || defined(__SAMD51J19A__) || defined(__SAMD51G19A__) || defined(__SAMD51P19A__) \ || defined(__SAMD21E15A__) || defined(__SAMD21E16A__) || defined(__SAMD21E17A__) || defined(__SAMD21E18A__) \ || defined(__SAMD21G15A__) || defined(__SAMD21G16A__) || defined(__SAMD21G17A__) || defined(__SAMD21G18A__) \ || defined(__SAMD21J15A__) || defined(__SAMD21J16A__) || defined(__SAMD21J17A__) || defined(__SAMD21J18A__) ) #if defined(WIFININA_USE_SAMD) #undef WIFININA_USE_SAMD #endif #define WIFININA_USE_SAMD true #endif #if defined(WIFININA_USE_SAMD) #if defined(ARDUINO_SAMD_ZERO) #define BOARD_TYPE "SAMD Zero" #elif defined(ARDUINO_SAMD_MKR1000) #define BOARD_TYPE "SAMD MKR1000" #define USING_WIFI101 true #elif defined(ARDUINO_SAMD_MKRWIFI1010) #define BOARD_TYPE "SAMD MKRWIFI1010" #define USING_WIFI101 true #elif defined(ARDUINO_SAMD_NANO_33_IOT) #define BOARD_TYPE "SAMD NANO_33_IOT" #elif defined(ARDUINO_SAMD_MKRFox1200) #define BOARD_TYPE "SAMD MKRFox1200" #elif ( defined(ARDUINO_SAMD_MKRWAN1300) || defined(ARDUINO_SAMD_MKRWAN1310) ) #define BOARD_TYPE "SAMD MKRWAN13X0" #elif defined(ARDUINO_SAMD_MKRGSM1400) #define BOARD_TYPE "SAMD MKRGSM1400" #elif defined(ARDUINO_SAMD_MKRNB1500) #define BOARD_TYPE "SAMD MKRNB1500" #elif defined(ARDUINO_SAMD_MKRVIDOR4000) #define BOARD_TYPE "SAMD MKRVIDOR4000" #elif defined(ARDUINO_SAMD_CIRCUITPLAYGROUND_EXPRESS) #define BOARD_TYPE "SAMD ARDUINO_SAMD_CIRCUITPLAYGROUND_EXPRESS" #elif defined(ADAFRUIT_FEATHER_M0_EXPRESS) #define BOARD_TYPE "SAMD21 ADAFRUIT_FEATHER_M0_EXPRESS" #elif defined(ADAFRUIT_METRO_M0_EXPRESS) #define BOARD_TYPE "SAMD21 ADAFRUIT_METRO_M0_EXPRESS" #elif defined(ADAFRUIT_CIRCUITPLAYGROUND_M0) #define BOARD_TYPE "SAMD21 ADAFRUIT_CIRCUITPLAYGROUND_M0" #elif defined(ADAFRUIT_GEMMA_M0) #define BOARD_TYPE "SAMD21 ADAFRUIT_GEMMA_M0" #elif defined(ADAFRUIT_TRINKET_M0) #define BOARD_TYPE "SAMD21 ADAFRUIT_TRINKET_M0" #elif defined(ADAFRUIT_ITSYBITSY_M0) #define BOARD_TYPE "SAMD21 ADAFRUIT_ITSYBITSY_M0" #elif defined(ARDUINO_SAMD_HALLOWING_M0) #define BOARD_TYPE "SAMD21 ARDUINO_SAMD_HALLOWING_M0" #elif defined(ADAFRUIT_METRO_M4_EXPRESS) #define BOARD_TYPE "SAMD51 ADAFRUIT_METRO_M4_EXPRESS" #elif defined(ADAFRUIT_GRAND_CENTRAL_M4) #define BOARD_TYPE "SAMD51 ADAFRUIT_GRAND_CENTRAL_M4" #elif defined(ADAFRUIT_FEATHER_M4_EXPRESS) #define BOARD_TYPE "SAMD51 ADAFRUIT_FEATHER_M4_EXPRESS" #elif defined(ADAFRUIT_ITSYBITSY_M4_EXPRESS) #define BOARD_TYPE "SAMD51 ADAFRUIT_ITSYBITSY_M4_EXPRESS" #elif defined(ADAFRUIT_TRELLIS_M4_EXPRESS) #define BOARD_TYPE "SAMD51 ADAFRUIT_TRELLIS_M4_EXPRESS" #elif defined(ADAFRUIT_PYPORTAL) #define BOARD_TYPE "SAMD51 ADAFRUIT_PYPORTAL" #elif defined(ADAFRUIT_PYPORTAL_M4_TITANO) #define BOARD_TYPE "SAMD51 ADAFRUIT_PYPORTAL_M4_TITANO" #elif defined(ADAFRUIT_PYBADGE_M4_EXPRESS) #define BOARD_TYPE "SAMD51 ADAFRUIT_PYBADGE_M4_EXPRESS" #elif defined(ADAFRUIT_METRO_M4_AIRLIFT_LITE) #define BOARD_TYPE "SAMD51 ADAFRUIT_METRO_M4_AIRLIFT_LITE" #elif defined(ADAFRUIT_PYGAMER_M4_EXPRESS) #define BOARD_TYPE "SAMD51 ADAFRUIT_PYGAMER_M4_EXPRESS" #elif defined(ADAFRUIT_PYGAMER_ADVANCE_M4_EXPRESS) #define BOARD_TYPE "SAMD51 ADAFRUIT_PYGAMER_ADVANCE_M4_EXPRESS" #elif defined(ADAFRUIT_PYBADGE_AIRLIFT_M4) #define BOARD_TYPE "SAMD51 ADAFRUIT_PYBADGE_AIRLIFT_M4" #elif defined(ADAFRUIT_MONSTER_M4SK_EXPRESS) #define BOARD_TYPE "SAMD51 ADAFRUIT_MONSTER_M4SK_EXPRESS" #elif defined(ADAFRUIT_HALLOWING_M4_EXPRESS) #define BOARD_TYPE "SAMD51 ADAFRUIT_HALLOWING_M4_EXPRESS" #elif defined(SEEED_WIO_TERMINAL) #define BOARD_TYPE "SAMD SEEED_WIO_TERMINAL" #elif defined(SEEED_FEMTO_M0) #define BOARD_TYPE "SAMD SEEED_FEMTO_M0" #elif defined(SEEED_XIAO_M0) #define BOARD_TYPE "SAMD SEEED_XIAO_M0" #elif defined(Wio_Lite_MG126) #define BOARD_TYPE "SAMD SEEED Wio_Lite_MG126" #elif defined(WIO_GPS_BOARD) #define BOARD_TYPE "SAMD SEEED WIO_GPS_BOARD" #elif defined(SEEEDUINO_ZERO) #define BOARD_TYPE "SAMD SEEEDUINO_ZERO" #elif defined(SEEEDUINO_LORAWAN) #define BOARD_TYPE "SAMD SEEEDUINO_LORAWAN" #elif defined(SEEED_GROVE_UI_WIRELESS) #define BOARD_TYPE "SAMD SEEED_GROVE_UI_WIRELESS" #elif defined(__SAMD21E18A__) #define BOARD_TYPE "SAMD21E18A" #elif defined(__SAMD21G18A__) #define BOARD_TYPE "SAMD21G18A" #elif defined(__SAMD51G19A__) #define BOARD_TYPE "SAMD51G19A" #elif defined(__SAMD51J19A__) #define BOARD_TYPE "SAMD51J19A" #elif defined(__SAMD51P19A__) #define BOARD_TYPE "__SAMD51P19A__" #elif defined(__SAMD51J20A__) #define BOARD_TYPE "SAMD51J20A" #elif defined(__SAM3X8E__) #define BOARD_TYPE "SAM3X8E" #elif defined(__CPU_ARC__) #define BOARD_TYPE "CPU_ARC" #elif defined(__SAMD51__) #define BOARD_TYPE "SAMD51" #else #define BOARD_TYPE "SAMD Unknown" #endif #endif #if ( defined(NRF52840_FEATHER) || defined(NRF52832_FEATHER) || defined(NRF52_SERIES) || defined(ARDUINO_NRF52_ADAFRUIT) || \ defined(NRF52840_FEATHER_SENSE) || defined(NRF52840_ITSYBITSY) || defined(NRF52840_CIRCUITPLAY) || defined(NRF52840_CLUE) || \ defined(NRF52840_METRO) || defined(NRF52840_PCA10056) || defined(PARTICLE_XENON) || defined(NINA_B302_ublox) || defined(NINA_B112_ublox) ) #if defined(WIFININA_USE_NRF52) #undef WIFININA_USE_NRF52 #endif #define WIFININA_USE_NRF52 true #endif #if defined(WIFININA_USE_NRF52) #if defined(NRF52840_FEATHER) #define BOARD_TYPE "NRF52840_FEATHER_EXPRESS" #elif defined(NRF52832_FEATHER) #define BOARD_TYPE "NRF52832_FEATHER" #elif defined(NRF52840_FEATHER_SENSE) #define BOARD_TYPE "NRF52840_FEATHER_SENSE" #elif defined(NRF52840_ITSYBITSY) #define BOARD_TYPE "NRF52840_ITSYBITSY_EXPRESS" #elif defined(NRF52840_CIRCUITPLAY) #define BOARD_TYPE "NRF52840_CIRCUIT_PLAYGROUND" #elif defined(NRF52840_CLUE) #define BOARD_TYPE "NRF52840_CLUE" #elif defined(NRF52840_METRO) #define BOARD_TYPE "NRF52840_METRO_EXPRESS" #elif defined(NRF52840_PCA10056) #define BOARD_TYPE "NORDIC_NRF52840DK" #elif defined(NINA_B302_ublox) #define BOARD_TYPE "NINA_B302_ublox" #elif defined(NINA_B112_ublox) #define BOARD_TYPE "NINA_B112_ublox" #elif defined(PARTICLE_XENON) #define BOARD_TYPE "PARTICLE_XENON" #elif defined(MDBT50Q_RX) #define BOARD_TYPE "RAYTAC_MDBT50Q_RX" #elif defined(ARDUINO_NRF52_ADAFRUIT) #define BOARD_TYPE "ARDUINO_NRF52_ADAFRUIT" #else #define BOARD_TYPE "nRF52 Unknown" #endif #endif #if ( defined(ARDUINO_SAM_DUE) || defined(__SAM3X8E__) ) #if defined(WIFININA_USE_SAMDUE) #undef WIFININA_USE_SAMDUE #endif #define WIFININA_USE_SAMDUE true #endif #if defined(WIFININA_USE_SAMDUE) // For SAM DUE #if defined(ARDUINO_SAM_DUE) #define BOARD_TYPE "SAM DUE" #elif defined(__SAM3X8E__) #define BOARD_TYPE "SAM SAM3X8E" #else #define BOARD_TYPE "SAM Unknown" #endif #endif #if ( defined(STM32F0) || defined(STM32F1) || defined(STM32F2) || defined(STM32F3) ||defined(STM32F4) || defined(STM32F7) || \ defined(STM32L0) || defined(STM32L1) || defined(STM32L4) || defined(STM32H7) ||defined(STM32G0) || defined(STM32G4) || \ defined(STM32WB) || defined(STM32MP1) ) #if defined(WIFININA_USE_STM32) #undef WIFININA_USE_STM32 #endif #define WIFININA_USE_STM32 true #endif #if defined(WIFININA_USE_STM32) #if defined(STM32F0) #warning STM32F0 board selected #define BOARD_TYPE "STM32F0" #elif defined(STM32F1) #warning STM32F1 board selected #define BOARD_TYPE "STM32F1" #elif defined(STM32F2) #warning STM32F2 board selected #define BOARD_TYPE "STM32F2" #elif defined(STM32F3) #warning STM32F3 board selected #define BOARD_TYPE "STM32F3" #elif defined(STM32F4) #warning STM32F4 board selected #define BOARD_TYPE "STM32F4" #elif defined(STM32F7) #warning STM32F7 board selected #define BOARD_TYPE "STM32F7" #elif defined(STM32L0) #warning STM32L0 board selected #define BOARD_TYPE "STM32L0" #elif defined(STM32L1) #warning STM32L1 board selected #define BOARD_TYPE "STM32L1" #elif defined(STM32L4) #warning STM32L4 board selected #define BOARD_TYPE "STM32L4" #elif defined(STM32H7) #warning STM32H7 board selected #define BOARD_TYPE "STM32H7" #elif defined(STM32G0) #warning STM32G0 board selected #define BOARD_TYPE "STM32G0" #elif defined(STM32G4) #warning STM32G4 board selected #define BOARD_TYPE "STM32G4" #elif defined(STM32WB) #warning STM32WB board selected #define BOARD_TYPE "STM32WB" #elif defined(STM32MP1) #warning STM32MP1 board selected #define BOARD_TYPE "STM32MP1" #else #warning STM32 unknown board selected #define BOARD_TYPE "STM32 Unknown" #endif #endif #ifdef CORE_TEENSY #if defined(WIFININA_USE_TEENSY) #undef WIFININA_USE_TEENSY #endif #define WIFININA_USE_TEENSY true #if defined(__IMXRT1062__) // For Teensy 4.1/4.0 #define BOARD_TYPE "TEENSY 4.1/4.0" #elif defined(__MK66FX1M0__) #define BOARD_TYPE "Teensy 3.6" #elif defined(__MK64FX512__) #define BOARD_TYPE "Teensy 3.5" #elif defined(__MKL26Z64__) #define BOARD_TYPE "Teensy LC" #elif defined(__MK20DX256__) #define BOARD_TYPE "Teensy 3.2" // and Teensy 3.1 (obsolete) #elif defined(__MK20DX128__) #define BOARD_TYPE "Teensy 3.0" #elif defined(__AVR_AT90USB1286__) #error Teensy 2.0++ not supported yet #elif defined(__AVR_ATmega32U4__) #error Teensy 2.0 not supported yet #else // For Other Boards #define BOARD_TYPE "Unknown Teensy Board" #endif #endif #if ( defined(ARDUINO_ARCH_RP2040) || defined(ARDUINO_RASPBERRY_PI_PICO) || defined(ARDUINO_ADAFRUIT_FEATHER_RP2040) || defined(ARDUINO_GENERIC_RP2040) ) #if defined(WIFININA_USE_RP2040) #undef WIFININA_USE_RP2040 #endif #define WIFININA_USE_RP2040 true #if defined(ARDUINO_ARCH_MBED) #if defined(BOARD_NAME) #undef BOARD_NAME #endif #if defined(ARDUINO_NANO_RP2040_CONNECT) #define BOARD_NAME "MBED NANO_RP2040_CONNECT" #elif defined(ARDUINO_RASPBERRY_PI_PICO) #define BOARD_NAME "MBED RASPBERRY_PI_PICO" #elif defined(ARDUINO_ADAFRUIT_FEATHER_RP2040) #define BOARD_NAME "MBED DAFRUIT_FEATHER_RP2040" #elif defined(ARDUINO_GENERIC_RP2040) #define BOARD_NAME "MBED GENERIC_RP2040" #else #define BOARD_NAME "MBED Unknown RP2040" #endif #endif #endif #if ( defined(__AVR_ATmega2560__) || defined(__AVR_ATmega2561__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega1281__) || \ defined(__AVR_ATmega640__) || defined(__AVR_ATmega641__)) #define BOARD_TYPE "Arduino AVR Mega2560/ADK" #warning Using Arduino AVR Mega, Mega640(P), Mega2560/ADK. #elif ( defined(__AVR_ATmega644__) || defined(__AVR_ATmega644A__) || defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644PA__) || \ defined(ARDUINO_AVR_UNO) || defined(ARDUINO_AVR_NANO) || defined(ARDUINO_AVR_MINI) || defined(ARDUINO_AVR_ETHERNET) || \ defined(ARDUINO_AVR_FIO) || defined(ARDUINO_AVR_BT) || defined(ARDUINO_AVR_LILYPAD) || defined(ARDUINO_AVR_PRO) || \ defined(ARDUINO_AVR_NG) || defined(ARDUINO_AVR_UNO_WIFI_DEV_ED) || defined(ARDUINO_AVR_DUEMILANOVE) ) #define BOARD_TYPE "Arduino AVR UNO, Nano, etc." #warning Using Aduino AVR ATMega644(P), ATMega328(P) such as UNO, Nano. #elif ( defined(ARDUINO_AVR_FEATHER328P) || defined(ARDUINO_AVR_METRO) || defined(ARDUINO_AVR_PROTRINKET5) || defined(ARDUINO_AVR_PROTRINKET3) || \ defined(ARDUINO_AVR_PROTRINKET5FTDI) || defined(ARDUINO_AVR_PROTRINKET3FTDI) ) #define BOARD_TYPE "Adafruit AVR ATMega328(P)" #warning Using Adafruit ATMega328(P), such as AVR_FEATHER328P or AVR_METRO. #elif ( defined(ARDUINO_AVR_LEONARDO) || defined(ARDUINO_AVR_LEONARDO_ETH) || defined(ARDUINO_AVR_YUN) || defined(ARDUINO_AVR_MICRO) || \ defined(ARDUINO_AVR_ESPLORA) || defined(ARDUINO_AVR_LILYPAD_USB) || defined(ARDUINO_AVR_ROBOT_CONTROL) || defined(ARDUINO_AVR_ROBOT_MOTOR) || \ defined(ARDUINO_AVR_CIRCUITPLAY) || defined(ARDUINO_AVR_YUNMINI) || defined(ARDUINO_AVR_INDUSTRIAL101) || defined(ARDUINO_AVR_LININO_ONE) ) #define BOARD_TYPE "Arduino AVR ATMega32U4" #warning Using Arduino ATMega32U4, such as Leonardo or Leonardo ETH. #elif ( defined(ARDUINO_AVR_FLORA8 ) || defined(ARDUINO_AVR_FEATHER32U4) || defined(ARDUINO_AVR_CIRCUITPLAY) || defined(ARDUINO_AVR_ITSYBITSY32U4_5V) || \ defined(ARDUINO_AVR_ITSYBITSY32U4_3V) || defined(ARDUINO_AVR_BLUEFRUITMICRO) || defined(ARDUINO_AVR_ADAFRUIT32U4) ) #define BOARD_TYPE "Adafruit AVR ATMega32U4" #warning Using Adafruit ATMega32U4, such as Feather_32u4, AVR_CIRCUITPLAY, etc. #elif ( defined(__AVR_ATmega32U4__) || defined(ARDUINO_AVR_MAKEYMAKEY ) || defined(ARDUINO_AVR_PROMICRO) || defined(ARDUINO_AVR_FIOV3) || \ defined(ARDUINO_AVR_QDUINOMINI) || defined(ARDUINO_AVR_LILYPAD_ARDUINO_USB_PLUS_BOARD ) ) #define BOARD_TYPE "Generic or Sparkfun AVR ATMega32U4" #warning Using Generic ATMega32U4, such as Sparkfun AVR_MAKEYMAKEY, AVR_PROMICRO, etc. #elif ( defined(__AVR_ATmega328P__) || defined(ARDUINO_AVR_DIGITAL_SANDBOX ) || defined(ARDUINO_REDBOT) || defined(ARDUINO_AVR_SERIAL_7_SEGMENT) ) #define BOARD_TYPE "Generic or Sparkfun AVR ATMega328P" #warning Using Generic ATMega328P, such as Sparkfun AVR_DIGITAL_SANDBOX, REDBOT, etc. #elif ( defined(__AVR_ATmega128RFA1__) || defined(ARDUINO_ATMEGA128RFA1_DEV_BOARD) ) #define BOARD_TYPE "Generic or Sparkfun AVR ATMega128RFA1" #warning Using Generic ATMega128RFA1, such as Sparkfun ATMEGA128RFA1_DEV_BOARD, etc. #elif ( defined(ARDUINO_AVR_GEMMA) || defined(ARDUINO_AVR_TRINKET3) || defined(ARDUINO_AVR_TRINKET5) ) #error These AVR boards are not supported! Please check your Tools->Board setting. #endif #if ( defined(__AVR_ATmega4809__) || defined(ARDUINO_AVR_UNO_WIFI_REV2) || defined(ARDUINO_AVR_NANO_EVERY) ) #if !defined(BOARD_NAME) #if (ARDUINO_AVR_UNO_WIFI_REV2) #define BOARD_NAME "megaAVR UNO WiFi Rev2" #elif (ARDUINO_AVR_NANO_EVERY) #define BOARD_NAME "megaAVR Nano Every" #else #define BOARD_NAME "megaAVR Unknown" #endif #endif #endif #ifndef BOARD_TYPE #define BOARD_TYPE "Unknown board" #endif #ifndef BOARD_NAME #define BOARD_NAME BOARD_TYPE #endif #define DEBUG_WIFININA_PORT Serial // Debug Level from 0 to 4 #define _WIFININA_LOGLEVEL_ 1 #define _WIFIMULTI_LOGLEVEL_ 2 #endif //defines_h
17,067
C++
.h
357
44.005602
154
0.703595
khoih-prog/WiFiNINA_Generic
36
12
0
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,538
arduino_secrets.h
khoih-prog_WiFiNINA_Generic/examples/WiFiMulti/WiFiUdpNtpClient_WiFiMulti/arduino_secrets.h
#define SECRET_SSID1 "your_ssid1" #define SECRET_PASS1 "your_pass1" #define SECRET_SSID2 "your_ssid2" #define SECRET_PASS2 "your_pass2"
152
C++
.h
4
37
37
0.702703
khoih-prog/WiFiNINA_Generic
36
12
0
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,542
WiFiNINA_Generic.h
khoih-prog_WiFiNINA_Generic/src/WiFiNINA_Generic.h
/********************************************************************************************************************************** WiFiNINA_Generic.h - Library for Arduino WiFiNINA module/shield. Based on and modified from WiFiNINA library https://www.arduino.cc/en/Reference/WiFiNINA to support nRF52, SAMD21/SAMD51, STM32F/L/H/G/WB/MP1, Teensy, etc. boards besides Nano-33 IoT, MKRWIFI1010, MKRVIDOR400, etc. Built by Khoi Hoang https://github.com/khoih-prog/WiFiNINA_Generic Licensed under MIT license Copyright (c) 2018 Arduino SA. All rights reserved. Copyright (c) 2011-2014 Arduino LLC. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Version: 1.8.15-1 Version Modified By Date Comments ------- ----------- ---------- ----------- 1.5.0 K Hoang 27/03/2020 Initial coding to support other boards besides Nano-33 IoT, MKRWIFI1010, MKRVIDOR4000, etc. such as Arduino Mega, Teensy, SAMD21, SAMD51, STM32, etc ... 1.8.13 K Hoang 03/08/2021 Sync with WiFiNINA v1.8.13 : new FW v1.4.8. Add support to ADAFRUIT_MATRIXPORTAL_M4_EXPRESS 1.8.14-1 K Hoang 25/11/2021 Fix examples to support ATmega4809 such as UNO_WIFI_REV2 and NANO_EVERY 1.8.14-2 K Hoang 31/12/2021 Add support to Nano_RP2040_Connect using arduino-pico core 1.8.14-3 K Hoang 31/12/2021 Fix issue with UDP for Nano_RP2040_Connect using arduino-pico core 1.8.14-4 K Hoang 01/05/2022 Fix bugs by using some PRs from original WiFiNINA. Add WiFiMulti-related examples 1.8.14-5 K Hoang 23/05/2022 Fix bug causing data lost when sending large files 1.8.14-6 K Hoang 17/08/2022 Add support to Teensy 4.x using WiFiNINA AirLift. Fix minor bug 1.8.14-7 K Hoang 11/11/2022 Modify WiFiWebServer example to avoid crash in arduino-pico core 1.8.15-0 K Hoang 14/11/2022 Fix severe limitation to permit sending much larger data than total 4K 1.8.15-1 K Hoang 18/11/2022 Using new WiFi101_Generic library to permit sending larger data than total 4K ***********************************************************************************************************************************/ #pragma once //////////////////////////////////////// #if !defined(USING_WIFI101_GENERIC) #define USING_WIFI101_GENERIC true #endif #if ( ( defined(ARDUINO_SAMD_MKR1000) || defined(ARDUINO_SAMD_MKRWIFI1010) ) && USING_WIFI101 ) #if USING_WIFI101_GENERIC #include <WiFi101_Generic.h> #warning Using WiFi101_Generic Library for MKR1000 and MKRWIFI1010 in WiFiNINA_Pinout_Generic.h #else #include <WiFi101.h> #warning Using WiFi101 Library for MKR1000 and MKRWIFI1010 in WiFiNINA_Pinout_Generic.h #endif #else #include "WiFi_Generic.h" #endif
3,452
C++
.h
52
62.673077
133
0.67021
khoih-prog/WiFiNINA_Generic
36
12
0
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,546
WiFiNINA_Pinout_Generic.h
khoih-prog_WiFiNINA_Generic/src/WiFiNINA_Pinout_Generic.h
/********************************************************************************************************************************** WiFiNINA_Pinout_Generic.h - Library for Arduino WiFiNINA module/shield. Based on and modified from WiFiNINA library https://www.arduino.cc/en/Reference/WiFiNINA to support nRF52, SAMD21/SAMD51, STM32F/L/H/G/WB/MP1, Teensy, etc. boards besides Nano-33 IoT, MKRWIFI1010, MKRVIDOR400, etc. Built by Khoi Hoang https://github.com/khoih-prog/WiFiNINA_Generic Licensed under MIT license Copyright (c) 2018 Arduino SA. All rights reserved. Copyright (c) 2011-2014 Arduino LLC. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Version: 1.8.15-1 Version Modified By Date Comments ------- ----------- ---------- ----------- 1.5.0 K Hoang 27/03/2020 Initial coding to support other boards besides Nano-33 IoT, MKRWIFI1010, MKRVIDOR4000, etc. such as Arduino Mega, Teensy, SAMD21, SAMD51, STM32, etc ... 1.8.13 K Hoang 03/08/2021 Sync with WiFiNINA v1.8.13 : new FW v1.4.8. Add support to ADAFRUIT_MATRIXPORTAL_M4_EXPRESS 1.8.14-1 K Hoang 25/11/2021 Fix examples to support ATmega4809 such as UNO_WIFI_REV2 and NANO_EVERY 1.8.14-2 K Hoang 31/12/2021 Add support to Nano_RP2040_Connect using arduino-pico core 1.8.14-3 K Hoang 31/12/2021 Fix issue with UDP for Nano_RP2040_Connect using arduino-pico core 1.8.14-4 K Hoang 01/05/2022 Fix bugs by using some PRs from original WiFiNINA. Add WiFiMulti-related examples 1.8.14-5 K Hoang 23/05/2022 Fix bug causing data lost when sending large files 1.8.14-6 K Hoang 17/08/2022 Add support to Teensy 4.x using WiFiNINA AirLift. Fix minor bug 1.8.14-7 K Hoang 11/11/2022 Modify WiFiWebServer example to avoid crash in arduino-pico core 1.8.15-0 K Hoang 14/11/2022 Fix severe limitation to permit sending much larger data than total 4K 1.8.15-1 K Hoang 18/11/2022 Using new WiFi101_Generic library to permit sending larger data than total 4K ***********************************************************************************************************************************/ #pragma once //////////////////////////////////////// /* For Nano-33-IoT, from hardware/samd/1.8.5/variants/nano33iot/variant.h/cpp +------------+------------------+--------+-----------------+--------+-----------------------+---------+---------+--------+--------+----------+----------+ | Pin number | MKR Board pin | PIN | Notes | Peri.A | Peripheral B | Perip.C | Perip.D | Peri.E | Peri.F | Periph.G | Periph.H | | | | | | EIC | ADC | AC | PTC | DAC | SERCOMx | SERCOMx | TCCx | TCCx | COM | AC/GLCK | | | | | |(EXTINT)|(AIN)|(AIN)| | | (x/PAD) | (x/PAD) | (x/WO) | (x/WO) | | | +------------+------------------+--------+-----------------+--------+-----+-----+-----+-----+---------+---------+--------+--------+----------+----------+ | |SPI (Legacy ICSP) | | | | | | | | | | | | | | +------------+------------------+--------+-----------------+--------+-----+-----+-----+-----+---------+---------+--------+--------+----------+----------+ | 22 | 1 | PA12 | NINA_MOSI | 12 | | | | | *2/00 | 4/00 | TCC2/0 | TCC0/6 | | AC/CMP0 | | 23 | 2 | PA13 | NINA_MISO | 13 | | | | | *2/01 | 4/01 | TCC2/1 | TCC0/7 | | AC/CMP1 | | 24 | 4 | PA14 | NINA_CS | 14 | | | | | 2/02 | 4/02 | TC3/0 | TCC0/4 | | GCLK_IO0 | | 25 | 3 | PA15 | NINA_SCK | 15 | | | | | *2/03 | 4/03 | TC3/1 | TCC0/5 | | GCLK_IO1 | | 26 | | PA27 | NINA_GPIO0 | *15 | | | | | | | | | | GCLK_IO0 | | 27 | | PA08 | NINA_RESETN | NMI | 16 | | X00 | | 0/00 | 2/00 | TCC0/0 | TCC1/2 | I2S/SD1 | | | 28 | | PA28 | NINA_ACK | 08 | | | | | | | | | | GCLK_IO0 | +------------+------------------+--------+-----------------+--------+-----+-----+-----+-----+---------+---------+--------+--------+----------+----------+ */ #if 0 // Example for Nano-33 IoT #define PINS_COUNT (PINCOUNT_fn()) #define NUM_DIGITAL_PINS (31u) #define NUM_ANALOG_INPUTS (8u) #define NUM_ANALOG_OUTPUTS (1u) //NINA #define NINA_GPIO0 (26u) //26 #define NINA_RESETN (27u) #define NINA_ACK (28u) // SPI1 #define PIN_SPI1_MISO (23u) #define PIN_SPI1_MOSI (22u) #define PIN_SPI1_SCK (25u) #define PIN_SPI1_SS (24u) #define PERIPH_SPI1 sercom2 #define PAD_SPI1_TX SPI_PAD_0_SCK_3 #define PAD_SPI1_RX SERCOM_RX_PAD_1 #define SPIWIFI_SS PIN_SPI1_SS //24 #define SPIWIFI_ACK NINA_ACK //28 #define SPIWIFI_RESET NINA_RESETN //27 #endif ////////////WARNING//////////////// // To modify according to actual connection //////////////////////////////////////// #if ( defined(ARDUINO_NANO_RP2040_CONNECT) || defined(ARDUINO_SAMD_NANO_33_IOT) || defined(ARDUINO_SAMD_MKRWIFI1010) || \ defined(ARDUINO_SAMD_MKRVIDOR4000) || defined(ARDUINO_ARDUINO_NANO_RP2040_CONNECT)) #if defined(ARDUINO_ARDUINO_NANO_RP2040_CONNECT) // Fix UDP issue for arduino-pico core #define NINA_GPIOIRQ (D20) // actual 2, NINA_GPIO0 #define NINA_RESETN (D24) // actual 3, NINA_RESETN #endif #if (_WIFININA_LOGLEVEL_>2) #warning Using default WiFiNINA settings #endif //////////////////////////////////////// #elif ( defined(ARDUINO_SAMD_ZERO) || defined(ARDUINO_SAMD_MKR1000) || defined(ARDUINO_SAMD_MKRWIFI1010) \ || defined(ARDUINO_SAMD_NANO_33_IOT) || defined(ARDUINO_SAMD_MKRFox1200) || defined(ARDUINO_SAMD_MKRWAN1300) || defined(ARDUINO_SAMD_MKRWAN1310) \ || defined(ARDUINO_SAMD_MKRGSM1400) || defined(ARDUINO_SAMD_MKRNB1500) || defined(ARDUINO_SAMD_MKRVIDOR4000) \ || defined(ARDUINO_SAMD_CIRCUITPLAYGROUND_EXPRESS) || defined(__SAMD51__) || defined(__SAMD51J20A__) \ || defined(__SAMD51J19A__) || defined(__SAMD51G19A__) || defined(__SAMD51P19A__) \ || defined(__SAMD21E15A__) || defined(__SAMD21E16A__) || defined(__SAMD21E17A__) || defined(__SAMD21E18A__) \ || defined(__SAMD21G15A__) || defined(__SAMD21G16A__) || defined(__SAMD21G17A__) || defined(__SAMD21G18A__) \ || defined(__SAMD21J15A__) || defined(__SAMD21J16A__) || defined(__SAMD21J17A__) || defined(__SAMD21J18A__) ) #if !( defined(ARDUINO_SAMD_NANO_33_IOT) || defined(ARDUINO_SAMD_MKRWIFI1010) || defined(ARDUINO_SAMD_MKRVIDOR4000) \ || defined(ARDUINO_SAM_DUE) || defined(__SAM3X8E__) ) #if defined(SEEED_WIO_TERMINAL) #warning You have to modify pin usage according to actual connection for SAMD SEEED_WIO_TERMINAL // To define pin out for WiFiNINA here //#define PINS_COUNT (60u) //NINA #define NINA_GPIO0 ( 0u) //0 #define NINA_RESETN ( 1u) #define NINA_ACK ( 2u) #define SPIWIFI_SS 3 //PIN_SPI1_SS //3 #define SPIWIFI_ACK 2 //NINA_ACK //2 #define SPIWIFI_RESET 1 //NINA_RESETN //1 #elif defined(SEEED_FEMTO_M0) #warning You have to modify pin usage according to actual connection for SAMD SEEED_FEMTO_M0 // To define pin out for WiFiNINA here //#define PINS_COUNT (60u) //NINA #define NINA_GPIO0 ( 0u) //0 #define NINA_RESETN ( 1u) #define NINA_ACK ( 2u) #define SPIWIFI_SS 3 //PIN_SPI1_SS //3 #define SPIWIFI_ACK 2 //NINA_ACK //2 #define SPIWIFI_RESET 1 //NINA_RESETN //1 #elif defined(SEEED_XIAO_M0) #warning You have to modify pin usage according to actual connection for SAMD SEEED_XIAO_M0 // To define pin out for WiFiNINA here //#define PINS_COUNT (60u) //NINA #define NINA_GPIO0 ( 0u) //0 #define NINA_RESETN ( 1u) #define NINA_ACK ( 2u) #define SPIWIFI_SS 3 //PIN_SPI1_SS //3 #define SPIWIFI_ACK 2 //NINA_ACK //2 #define SPIWIFI_RESET 1 //NINA_RESETN //1 #elif defined(Wio_Lite_MG126) #warning You have to modify pin usage according to actual connection for SAMD Wio_Lite_MG126 // To define pin out for WiFiNINA here //#define PINS_COUNT (60u) //NINA #define NINA_GPIO0 ( 0u) //0 #define NINA_RESETN ( 1u) #define NINA_ACK ( 2u) #define SPIWIFI_SS 3 //PIN_SPI1_SS //3 #define SPIWIFI_ACK 2 //NINA_ACK //2 #define SPIWIFI_RESET 1 //NINA_RESETN //1 #elif defined(WIO_GPS_BOARD) #warning You have to modify pin usage according to actual connection for SAMD WIO_GPS_BOARD // To define pin out for WiFiNINA here //#define PINS_COUNT (60u) //NINA #define NINA_GPIO0 ( 0u) //0 #define NINA_RESETN ( 1u) #define NINA_ACK ( 2u) #define SPIWIFI_SS 3 //PIN_SPI1_SS //3 #define SPIWIFI_ACK 2 //NINA_ACK //2 #define SPIWIFI_RESET 1 //NINA_RESETN //1 #elif defined(SEEEDUINO_ZERO) #warning You have to modify pin usage according to actual connection for SAMD SEEEDUINO_ZERO // To define pin out for WiFiNINA here //#define PINS_COUNT (60u) //NINA #define NINA_GPIO0 ( 0u) //0 #define NINA_RESETN ( 1u) #define NINA_ACK ( 2u) #define SPIWIFI_SS 3 //PIN_SPI1_SS //3 #define SPIWIFI_ACK 2 //NINA_ACK //2 #define SPIWIFI_RESET 1 //NINA_RESETN //1 #elif defined(SEEEDUINO_LORAWAN) #warning You have to modify pin usage according to actual connection for SAMD SEEEDUINO_LORAWAN // To define pin out for WiFiNINA here //#define PINS_COUNT (60u) //NINA #define NINA_GPIO0 ( 0u) //0 #define NINA_RESETN ( 1u) #define NINA_ACK ( 2u) #define SPIWIFI_SS 3 //PIN_SPI1_SS //3 #define SPIWIFI_ACK 2 //NINA_ACK //2 #define SPIWIFI_RESET 1 //NINA_RESETN //1 #elif defined(SEEED_GROVE_UI_WIRELESS) #warning You have to modify pin usage according to actual connection for SAMD SEEED_GROVE_UI_WIRELESS // To define pin out for WiFiNINA here //#define PINS_COUNT (60u) //NINA #define NINA_GPIO0 ( 0u) //0 #define NINA_RESETN ( 1u) #define NINA_ACK ( 2u) #define SPIWIFI_SS 3 //PIN_SPI1_SS //3 #define SPIWIFI_ACK 2 //NINA_ACK //2 #define SPIWIFI_RESET 1 //NINA_RESETN //1 #elif ( defined(ADAFRUIT_METRO_M4_AIRLIFT_LITE) || defined(ADAFRUIT_PYBADGE_AIRLIFT_M4) ) #if (_WIFININA_LOGLEVEL_>2) #warning ADAFRUIT_METRO_M4_AIRLIFT_LITE or ADAFRUIT_PYBADGE_AIRLIFT_M4 are OK to use #endif #elif ( defined(ADAFRUIT_MATRIXPORTAL_M4_EXPRESS) ) #warning You have to modify pin usage according to actual connection for SAMD51 ADAFRUIT_MATRIXPORTAL_M4_EXPRESS // To define pin out for WiFiNINA here //#define PINS_COUNT (60u) //NINA #define NINA_GPIO0 ESP32_GPIO0 #define NINA_RESETN ESP32_RESETN #define NINA_ACK SPIWIFI_ACK #define SPIWIFI_SS 33 #define SPIWIFI_ACK 31 #define SPIWIFI_RESET ESP32_RESETN #else #warning You have to modify pin usage according to actual connection for SAMD // To define pin out for WiFiNINA here //#define PINS_COUNT (60u) //NINA #define NINA_GPIO0 (26u) //26 #define NINA_RESETN (27u) #define NINA_ACK (28u) #define SPIWIFI_SS 24 //PIN_SPI1_SS //24 #define SPIWIFI_ACK 28 //NINA_ACK //28 #define SPIWIFI_RESET 27 //NINA_RESETN //27 #endif #endif //////////////////////////////////////// #elif ( defined(NRF52840_FEATHER) || defined(NRF52832_FEATHER) || defined(NRF52_SERIES) || defined(ARDUINO_NRF52_ADAFRUIT) || \ defined(NRF52840_FEATHER_SENSE) || defined(NRF52840_ITSYBITSY) || defined(NRF52840_CIRCUITPLAY) || defined(NRF52840_CLUE) || \ defined(NRF52840_METRO) || defined(NRF52840_PCA10056) || defined(PARTICLE_XENON) || defined(NINA_B302_ublox) || defined(NINA_B112_ublox) ) #if ( defined(NINA_B302_ublox) ) #warning You have to modify pin usage according to actual connection for NINA_B302_ublox running as NRF52840 // To define pin out for WiFiNINA here. This is just an example and tested working OK. // The following is for NINA_B302_ublox as nRF52840 and W102 WiFiNINA module // Thanks to great work of [Miguel Alexandre Wisintainer](https://github.com/tcpipchip). // See [u-blox nina b](https://github.com/khoih-prog/WiFiNINA_Generic/issues/1) //#define PINS_COUNT (60u) //NINA #define NINA_GPIO0 (22u) // 22, IO4, P0.16 #define NINA_RESETN (2u) // 2, IO21, P0.12 #define NINA_ACK (10u) // 10, IO2, P0.14 #define SPIWIFI_SS 4 //PIN_SPI1_SS // 4, IO1, P0.13 #define SPIWIFI_ACK 10 //NINA_ACK // 10, IO2, P0.14 #define SPIWIFI_RESET 2 //NINA_RESETN // 2, IO21, P0.12 #elif ( defined(NINA_B112_ublox) ) #warning You have to modify pin usage according to actual connection for NINA_B112_ublox running as NRF52832 // To define pin out for WiFiNINA here. This is just an example and tested working OK. // The following is for NINA_B112_ublox as nRF52832 and W102 WiFiNINA module // Thanks to great work of [Miguel Alexandre Wisintainer](https://github.com/tcpipchip). // See [u-blox nina b](https://github.com/khoih-prog/WiFiNINA_Generic/issues/1) //#define PINS_COUNT (60u) //NINA #define NINA_GPIO0 (22u) // 22, IO4, P0.16 #define NINA_RESETN (2u) // 2, IO21, P0.12 #define NINA_ACK (10u) // 10, IO2, P0.14 #define SPIWIFI_SS 4 //PIN_SPI1_SS // 4, IO1, P0.13 #define SPIWIFI_ACK 10 //NINA_ACK // 10, IO2, P0.14 #define SPIWIFI_RESET 2 //NINA_RESETN // 2, IO21, P0.12 #else #warning You have to modify pin usage according to actual connection for NRF528XX board // To define pin out for WiFiNINA here. This is just an example // The following is for NINA_B302_ublox as nRF52 and W102 WiFiNINA module // Thanks to great work of [Miguel Alexandre Wisintainer](https://github.com/tcpipchip). // See [u-blox nina b](https://github.com/khoih-prog/WiFiNINA_Generic/issues/1) //#define PINS_COUNT (60u) //NINA #define NINA_GPIO0 (12u) // 12, IO8, P1.00 #define NINA_RESETN (2u) // 2, IO21, P0.12 #define NINA_ACK (10u) // 10, IO2, P0.14 #define SPIWIFI_SS 4 //PIN_SPI1_SS // 4, IO1, P0.13 #define SPIWIFI_ACK 10 //NINA_ACK // 10, IO2, P0.14 #define SPIWIFI_RESET 2 //NINA_RESETN // 2, IO21, P0.12 #endif //////////////////////////////////////// #elif ( defined(ARDUINO_AVR_MEGA) || defined(ARDUINO_AVR_MEGA2560) || defined(AVR_ADK) ) #warning You have to modify pin usage according to actual connection for Mega 2560/1280 // To define pin out for WiFiNINA here //#define PIN_SPI_SS (53) //#define PIN_SPI_MOSI (51) //#define PIN_SPI_MISO (50) //#define PIN_SPI_SCK (52) #define PINS_COUNT (60u) //NINA #define NINA_GPIO0 (26u) //26 #define NINA_RESETN (27u) #define NINA_ACK (28u) #define SPIWIFI_SS 53 //PIN_SPI_SS //53 #define SPIWIFI_ACK 28 //NINA_ACK //28 #define SPIWIFI_RESET 27 //NINA_RESETN //27 //////////////////////////////////////// #elif ( defined(ARDUINO_AVR_UNO_WIFI_REV2) ) #if (_WIFININA_LOGLEVEL_>2) #warning Use WiFiNINA for UNO WiFi Rev2 #endif //////////////////////////////////////// #elif defined(CORE_TEENSY) #if defined(__IMXRT1062__) // For Teensy 4.0 #warning You have to modify pin usage according to actual connection for Teensy 4.0/4.1 #define PINS_COUNT (60u) // T4.1 SPI pin defs for WiFiNINA AirLift. #define NINA_GPIO0 (255u) //6 #define NINA_RESETN (6u) #define NINA_ACK (9u) // T4.1 SPI pin defs for WiFiNINA AirLift. #define SPIWIFI_SS 5 //PIN_SPI1_SS //10 #define SPIWIFI_ACK 9 //NINA_ACK //7 #define SPIWIFI_RESET 6 //NINA_RESETN //5 #elif ( defined(__MKL26Z64__) || defined(ARDUINO_ARCH_AVR) ) // For BOARD_TYPE "TEENSY LC or 2.0" #warning You have to modify pin usage according to actual connection for Teensy LC or 2.0 #define PINS_COUNT (60u) //NINA #define NINA_GPIO0 (6u) //6 #define NINA_RESETN (2u) #define NINA_ACK (5u) #define SPIWIFI_SS 10 //PIN_SPI1_SS //10 #define SPIWIFI_ACK 5 //NINA_ACK //5 #define SPIWIFI_RESET 2 //NINA_RESETN //7 #else #warning You have to modify pin usage according to actual connection for Teensy 3.x #define PINS_COUNT (60u) //NINA #define NINA_GPIO0 (6u) //6 #define NINA_RESETN (2u) #define NINA_ACK (5u) #define SPIWIFI_SS 10 //PIN_SPI1_SS //10 #define SPIWIFI_ACK 5 //NINA_ACK //5 #define SPIWIFI_RESET 2 //NINA_RESETN //7 #endif //////////////////////////////////////// #elif ( defined(ARDUINO_SAM_DUE) || defined(__SAM3X8E__) ) #warning You have to modify pin usage according to actual connection for SAM DUE //#define PINS_COUNT (60u) //NINA #define NINA_GPIO0 (26u) //26 #define NINA_RESETN (27u) #define NINA_ACK (28u) #define SPIWIFI_SS 24 //PIN_SPI1_SS //24 #define SPIWIFI_ACK 28 //NINA_ACK //28 #define SPIWIFI_RESET 27 //NINA_RESETN //27 //////////////////////////////////////// #elif ( defined(STM32F0) || defined(STM32F1) || defined(STM32F2) || defined(STM32F3) ||defined(STM32F4) || defined(STM32F7) || \ defined(STM32L0) || defined(STM32L1) || defined(STM32L4) || defined(STM32H7) ||defined(STM32G0) || defined(STM32G4) || \ defined(STM32WB) || defined(STM32MP1) ) #if defined(ARDUINO_NUCLEO_L053R8) // For Nucleo-64 NUCLEO_L053R8 #warning You have to modify pin usage according to actual connection for NUCLEO_L053R8 #define PINS_COUNT (60u) //NINA #define NINA_GPIO0 (6u) //not used #define NINA_RESETN (D2) #define NINA_ACK (D3) #define SPIWIFI_SS D10 //PIN_SPI1_SS //10 #define SPIWIFI_ACK D3 //NINA_ACK //3 #define SPIWIFI_RESET D2 //NINA_RESETN //2 #else #warning You have to modify pin usage according to actual connection for STM32 #define PINS_COUNT (60u) //NINA #define NINA_GPIO0 (26u) //26 #define NINA_RESETN (27u) #define NINA_ACK (28u) #define SPIWIFI_SS 24 //PIN_SPI1_SS //24 #define SPIWIFI_ACK 28 //NINA_ACK //28 #define SPIWIFI_RESET 27 //NINA_RESETN //27 #endif //////////////////////////////////////// #elif ( defined(ARDUINO_ARCH_RP2040) || defined(ARDUINO_RASPBERRY_PI_PICO) || defined(ARDUINO_ADAFRUIT_FEATHER_RP2040) || \ defined(ARDUINO_GENERIC_RP2040) || defined(ARDUINO_ARDUINO_NANO_RP2040_CONNECT) ) #if defined(ARDUINO_ARDUINO_NANO_RP2040_CONNECT) #if (_WIFININA_LOGLEVEL_>2) #warning Using Nano_RP2040_Connect with arduino-pico core #endif //NINA #define NINA_GPIO0 (20u) #define NINA_RESETN (24u) #define NINA_ACK (27u) #define SPIWIFI_SS (26u) #define SPIWIFI_ACK (27u) #define SPIWIFI_RESET (NINA_RESETN) #else #warning You have to modify pin usage according to actual connection for RP2040 //NINA #define NINA_GPIO0 (20u) #define NINA_RESETN (24u) #define NINA_ACK (27u) #define SPIWIFI_SS (26u) #define SPIWIFI_ACK (27u) #define SPIWIFI_RESET (NINA_RESETN) #endif //////////////////////////////////////// #elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega1281__) || \ defined(__AVR_ATmega640__) || defined(__AVR_ATmega641__) || defined(__AVR_ATmega644__) || defined(__AVR_ATmega644A__) || \ defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644PA__) || defined(ARDUINO_AVR_UNO) || defined(ARDUINO_AVR_NANO) || \ defined(ARDUINO_AVR_MINI) || defined(ARDUINO_AVR_ETHERNET) || defined(ARDUINO_AVR_FIO) || defined(ARDUINO_AVR_BT) || \ defined(ARDUINO_AVR_LILYPAD) || defined(ARDUINO_AVR_PRO) || defined(ARDUINO_AVR_NG) || defined(ARDUINO_AVR_UNO_WIFI_DEV_ED) || \ defined(ARDUINO_AVR_DUEMILANOVE) || defined(ARDUINO_AVR_FEATHER328P) || defined(ARDUINO_AVR_METRO) || defined(ARDUINO_AVR_PROTRINKET5) || \ defined(ARDUINO_AVR_PROTRINKET3) || defined(ARDUINO_AVR_PROTRINKET5FTDI) || defined(ARDUINO_AVR_PROTRINKET3FTDI) || \ defined(ARDUINO_AVR_LEONARDO) || defined(ARDUINO_AVR_LEONARDO_ETH) || defined(ARDUINO_AVR_YUN) || defined(ARDUINO_AVR_MICRO) || \ defined(ARDUINO_AVR_ESPLORA) || defined(ARDUINO_AVR_LILYPAD_USB) || defined(ARDUINO_AVR_ROBOT_CONTROL) || \ defined(ARDUINO_AVR_ROBOT_MOTOR) || defined(ARDUINO_AVR_CIRCUITPLAY) || defined(ARDUINO_AVR_YUNMINI) || defined(ARDUINO_AVR_INDUSTRIAL101) || \ defined(ARDUINO_AVR_LININO_ONE) || defined(ARDUINO_AVR_FLORA8 ) || defined(ARDUINO_AVR_FEATHER32U4) || defined(ARDUINO_AVR_CIRCUITPLAY) || \ defined(ARDUINO_AVR_ITSYBITSY32U4_5V) || defined(ARDUINO_AVR_ITSYBITSY32U4_3V) || defined(ARDUINO_AVR_BLUEFRUITMICRO) || \ defined(ARDUINO_AVR_ADAFRUIT32U4) || defined(__AVR_ATmega32U4__) || defined(ARDUINO_AVR_MAKEYMAKEY ) || defined(ARDUINO_AVR_PROMICRO) || \ defined(ARDUINO_AVR_FIOV3) || defined(ARDUINO_AVR_QDUINOMINI) || defined(ARDUINO_AVR_LILYPAD_ARDUINO_USB_PLUS_BOARD ) || \ defined(__AVR_ATmega328P__) || defined(ARDUINO_AVR_DIGITAL_SANDBOX ) || defined(ARDUINO_REDBOT) || defined(ARDUINO_AVR_SERIAL_7_SEGMENT) || \ defined(__AVR_ATmega128RFA1__) || defined(ARDUINO_ATMEGA128RFA1_DEV_BOARD) // To define pin out for WiFiNINA here //#define PIN_SPI_SS (4) //#define PIN_SPI_MOSI (11) //#define PIN_SPI_MISO (12) //#define PIN_SPI_SCK (13) #define PINS_COUNT (60u) //NINA #define NINA_GPIO0 (2u) #define NINA_RESETN (7u) #define NINA_ACK (8u) #define SPIWIFI_SS 4 #define SPIWIFI_ACK 8 #define SPIWIFI_RESET 7 #warning You have to modify pin usage according to actual connection for AVR (328P, 32U4, 16U4, etc.) boards //////////////////////////////////////// #else #warning You have to modify pin usage according to actual connection for your unknown board #define PINS_COUNT (60u) //NINA #define NINA_GPIO0 (26u) //26 #define NINA_RESETN (27u) #define NINA_ACK (28u) #define SPIWIFI_SS 10 //PIN_SPI_SS //10 #define SPIWIFI_ACK 28 //NINA_ACK //28 #define SPIWIFI_RESET 27 //NINA_RESETN //27 //////////////////////////////////////// #endif
25,007
C++
.h
425
55.665882
155
0.56465
khoih-prog/WiFiNINA_Generic
36
12
0
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,547
wl_types.h
khoih-prog_WiFiNINA_Generic/src/utility/wl_types.h
/********************************************************************************************************************************** wl_types.h - Library for Arduino WiFiNINA module/shield. Based on and modified from WiFiNINA library https://www.arduino.cc/en/Reference/WiFiNINA to support nRF52, SAMD21/SAMD51, STM32F/L/H/G/WB/MP1, Teensy, etc. boards besides Nano-33 IoT, MKRWIFI1010, MKRVIDOR400, etc. Built by Khoi Hoang https://github.com/khoih-prog/WiFiNINA_Generic Licensed under MIT license Copyright (c) 2018 Arduino SA. All rights reserved. Copyright (c) 2011-2014 Arduino LLC. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Version: 1.8.15-1 Version Modified By Date Comments ------- ----------- ---------- ----------- 1.5.0 K Hoang 27/03/2020 Initial coding to support other boards besides Nano-33 IoT, MKRWIFI1010, MKRVIDOR4000, etc. such as Arduino Mega, Teensy, SAMD21, SAMD51, STM32, etc ... 1.8.13 K Hoang 03/08/2021 Sync with WiFiNINA v1.8.13 : new FW v1.4.8. Add support to ADAFRUIT_MATRIXPORTAL_M4_EXPRESS 1.8.14-1 K Hoang 25/11/2021 Fix examples to support ATmega4809 such as UNO_WIFI_REV2 and NANO_EVERY 1.8.14-2 K Hoang 31/12/2021 Add support to Nano_RP2040_Connect using arduino-pico core 1.8.14-3 K Hoang 31/12/2021 Fix issue with UDP for Nano_RP2040_Connect using arduino-pico core 1.8.14-4 K Hoang 01/05/2022 Fix bugs by using some PRs from original WiFiNINA. Add WiFiMulti-related examples 1.8.14-5 K Hoang 23/05/2022 Fix bug causing data lost when sending large files 1.8.14-6 K Hoang 17/08/2022 Add support to Teensy 4.x using WiFiNINA AirLift. Fix minor bug 1.8.14-7 K Hoang 11/11/2022 Modify WiFiWebServer example to avoid crash in arduino-pico core 1.8.15-0 K Hoang 14/11/2022 Fix severe limitation to permit sending much larger data than total 4K 1.8.15-1 K Hoang 18/11/2022 Using new WiFi101_Generic library to permit sending larger data than total 4K ***********************************************************************************************************************************/ #pragma once /******************************* wl_types.h Created on: Jul 30, 2010 Author: dlafauci *******************************/ #include <inttypes.h> //////////////////////////////////////// typedef enum { WL_FAILURE = -1, WL_SUCCESS = 1, } wl_error_code_t; //////////////////////////////////////// /* Authentication modes */ enum wl_auth_mode { AUTH_MODE_INVALID, AUTH_MODE_AUTO, AUTH_MODE_OPEN_SYSTEM, AUTH_MODE_SHARED_KEY, AUTH_MODE_WPA, AUTH_MODE_WPA2, AUTH_MODE_WPA_PSK, AUTH_MODE_WPA2_PSK }; //////////////////////////////////////// typedef enum { WL_PING_DEST_UNREACHABLE = -1, WL_PING_TIMEOUT = -2, WL_PING_UNKNOWN_HOST = -3, WL_PING_ERROR = -4 } wl_ping_result_t; ////////////////////////////////////////
3,672
C++
.h
71
48.380282
133
0.61938
khoih-prog/WiFiNINA_Generic
36
12
0
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,548
wifi_spi.h
khoih-prog_WiFiNINA_Generic/src/utility/wifi_spi.h
/********************************************************************************************************************************** wifi_spi.h - Library for Arduino WiFiNINA module/shield. Based on and modified from WiFiNINA library https://www.arduino.cc/en/Reference/WiFiNINA to support nRF52, SAMD21/SAMD51, STM32F/L/H/G/WB/MP1, Teensy, etc. boards besides Nano-33 IoT, MKRWIFI1010, MKRVIDOR400, etc. Built by Khoi Hoang https://github.com/khoih-prog/WiFiNINA_Generic Licensed under MIT license Copyright (c) 2018 Arduino SA. All rights reserved. Copyright (c) 2011-2014 Arduino LLC. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Version: 1.8.15-1 Version Modified By Date Comments ------- ----------- ---------- ----------- 1.5.0 K Hoang 27/03/2020 Initial coding to support other boards besides Nano-33 IoT, MKRWIFI1010, MKRVIDOR4000, etc. such as Arduino Mega, Teensy, SAMD21, SAMD51, STM32, etc ... 1.8.13 K Hoang 03/08/2021 Sync with WiFiNINA v1.8.13 : new FW v1.4.8. Add support to ADAFRUIT_MATRIXPORTAL_M4_EXPRESS 1.8.14-1 K Hoang 25/11/2021 Fix examples to support ATmega4809 such as UNO_WIFI_REV2 and NANO_EVERY 1.8.14-2 K Hoang 31/12/2021 Add support to Nano_RP2040_Connect using arduino-pico core 1.8.14-3 K Hoang 31/12/2021 Fix issue with UDP for Nano_RP2040_Connect using arduino-pico core 1.8.14-4 K Hoang 01/05/2022 Fix bugs by using some PRs from original WiFiNINA. Add WiFiMulti-related examples 1.8.14-5 K Hoang 23/05/2022 Fix bug causing data lost when sending large files 1.8.14-6 K Hoang 17/08/2022 Add support to Teensy 4.x using WiFiNINA AirLift. Fix minor bug 1.8.14-7 K Hoang 11/11/2022 Modify WiFiWebServer example to avoid crash in arduino-pico core 1.8.15-0 K Hoang 14/11/2022 Fix severe limitation to permit sending much larger data than total 4K 1.8.15-1 K Hoang 18/11/2022 Using new WiFi101_Generic library to permit sending larger data than total 4K ***********************************************************************************************************************************/ #pragma once #include <inttypes.h> #include "utility/wl_definitions.h" //////////////////////////////////////// #define CMD_FLAG 0 #define REPLY_FLAG 1<<7 #define DATA_FLAG 0x40 //////////////////////////////////////// #define WIFI_SPI_ACK 1 #define WIFI_SPI_ERR 0xFF //////////////////////////////////////// #define TIMEOUT_CHAR 1000 //////////////////////////////////////// //#define MAX_SOCK_NUM 4 /**< Maxmimum number of socket */ #define NO_SOCKET_AVAIL 255 //////////////////////////////////////// #define START_CMD 0xE0 #define END_CMD 0xEE #define ERR_CMD 0xEF #define CMD_POS 1 // Position of Command OpCode on SPI stream #define PARAM_LEN_POS 2 // Position of Param len on SPI stream //////////////////////////////////////// enum { SET_NET_CMD = 0x10, SET_PASSPHRASE_CMD = 0x11, SET_KEY_CMD = 0x12, // TEST_CMD = 0x13, SET_IP_CONFIG_CMD = 0x14, SET_DNS_CONFIG_CMD = 0x15, SET_HOSTNAME_CMD = 0x16, SET_POWER_MODE_CMD = 0x17, SET_AP_NET_CMD = 0x18, SET_AP_PASSPHRASE_CMD = 0x19, SET_DEBUG_CMD = 0x1A, GET_TEMPERATURE_CMD = 0x1B, GET_REASON_CODE_CMD = 0x1F, GET_CONN_STATUS_CMD = 0x20, GET_IPADDR_CMD = 0x21, GET_MACADDR_CMD = 0x22, GET_CURR_SSID_CMD = 0x23, GET_CURR_BSSID_CMD = 0x24, GET_CURR_RSSI_CMD = 0x25, GET_CURR_ENCT_CMD = 0x26, SCAN_NETWORKS = 0x27, START_SERVER_TCP_CMD = 0x28, GET_STATE_TCP_CMD = 0x29, DATA_SENT_TCP_CMD = 0x2A, AVAIL_DATA_TCP_CMD = 0x2B, GET_DATA_TCP_CMD = 0x2C, START_CLIENT_TCP_CMD = 0x2D, STOP_CLIENT_TCP_CMD = 0x2E, GET_CLIENT_STATE_TCP_CMD = 0x2F, DISCONNECT_CMD = 0x30, // GET_IDX_SSID_CMD = 0x31, GET_IDX_RSSI_CMD = 0x32, GET_IDX_ENCT_CMD = 0x33, REQ_HOST_BY_NAME_CMD = 0x34, GET_HOST_BY_NAME_CMD = 0x35, START_SCAN_NETWORKS = 0x36, GET_FW_VERSION_CMD = 0x37, // GET_TEST_CMD = 0x38, SEND_DATA_UDP_CMD = 0x39, GET_REMOTE_DATA_CMD = 0x3A, GET_TIME_CMD = 0x3B, GET_IDX_BSSID = 0x3C, GET_IDX_CHANNEL_CMD = 0x3D, PING_CMD = 0x3E, GET_SOCKET_CMD = 0x3F, // All command with DATA_FLAG 0x40 send a 16bit Len SET_ENT_CMD = 0x40, SEND_DATA_TCP_CMD = 0x44, GET_DATABUF_TCP_CMD = 0x45, INSERT_DATABUF_CMD = 0x46, // regular format commands SET_PIN_MODE = 0x50, SET_DIGITAL_WRITE = 0x51, SET_ANALOG_WRITE = 0x52, GET_DIGITAL_READ = 0x53, GET_ANALOG_READ = 0x54, // regular format commands WRITE_FILE = 0x60, READ_FILE = 0x61, DELETE_FILE = 0x62, EXISTS_FILE = 0x63, DOWNLOAD_FILE = 0x64, APPLY_OTA_COMMAND = 0x65, RENAME_FILE = 0x66, // New from v1.7.0 DOWNLOAD_OTA = 0x67, ////// }; //////////////////////////////////////// enum wl_tcp_state { CLOSED = 0, LISTEN = 1, SYN_SENT = 2, SYN_RCVD = 3, ESTABLISHED = 4, FIN_WAIT_1 = 5, FIN_WAIT_2 = 6, CLOSE_WAIT = 7, CLOSING = 8, LAST_ACK = 9, TIME_WAIT = 10 }; //////////////////////////////////////// enum numParams { PARAM_NUMS_0, PARAM_NUMS_1, PARAM_NUMS_2, PARAM_NUMS_3, PARAM_NUMS_4, PARAM_NUMS_5, PARAM_NUMS_6, MAX_PARAM_NUMS }; //////////////////////////////////////// #define MAX_PARAMS MAX_PARAM_NUMS-1 #define PARAM_LEN_SIZE 1 //////////////////////////////////////// typedef struct __attribute__((__packed__)) { uint8_t paramLen; char* param; } tParam; //////////////////////////////////////// typedef struct __attribute__((__packed__)) { uint16_t dataLen; char* data; } tDataParam; //////////////////////////////////////// typedef struct __attribute__((__packed__)) { unsigned char cmd; unsigned char tcmd; unsigned char nParam; tParam params[MAX_PARAMS]; } tSpiMsg; typedef struct __attribute__((__packed__)) { unsigned char cmd; unsigned char tcmd; unsigned char nParam; tDataParam params[MAX_PARAMS]; } tSpiMsgData; //////////////////////////////////////// typedef struct __attribute__((__packed__)) { unsigned char cmd; unsigned char tcmd; //unsigned char totLen; unsigned char nParam; } tSpiHdr; //////////////////////////////////////// typedef struct __attribute__((__packed__)) { uint8_t paramLen; uint32_t param; } tLongParam; //////////////////////////////////////// typedef struct __attribute__((__packed__)) { uint8_t paramLen; uint16_t param; } tIntParam; //////////////////////////////////////// typedef struct __attribute__((__packed__)) { uint8_t paramLen; uint8_t param; } tByteParam; ////////////////////////////////////////
7,814
C++
.h
220
32.840909
133
0.568342
khoih-prog/WiFiNINA_Generic
36
12
0
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,549
wl_definitions.h
khoih-prog_WiFiNINA_Generic/src/utility/wl_definitions.h
/********************************************************************************************************************************** wl_definitions.h - Library for Arduino WiFiNINA module/shield. Based on and modified from WiFiNINA library https://www.arduino.cc/en/Reference/WiFiNINA to support nRF52, SAMD21/SAMD51, STM32F/L/H/G/WB/MP1, Teensy, etc. boards besides Nano-33 IoT, MKRWIFI1010, MKRVIDOR400, etc. Built by Khoi Hoang https://github.com/khoih-prog/WiFiNINA_Generic Licensed under MIT license Copyright (c) 2018 Arduino SA. All rights reserved. Copyright (c) 2011-2014 Arduino LLC. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Version: 1.8.15-1 Version Modified By Date Comments ------- ----------- ---------- ----------- 1.5.0 K Hoang 27/03/2020 Initial coding to support other boards besides Nano-33 IoT, MKRWIFI1010, MKRVIDOR4000, etc. such as Arduino Mega, Teensy, SAMD21, SAMD51, STM32, etc ... 1.8.13 K Hoang 03/08/2021 Sync with WiFiNINA v1.8.13 : new FW v1.4.8. Add support to ADAFRUIT_MATRIXPORTAL_M4_EXPRESS 1.8.14-1 K Hoang 25/11/2021 Fix examples to support ATmega4809 such as UNO_WIFI_REV2 and NANO_EVERY 1.8.14-2 K Hoang 31/12/2021 Add support to Nano_RP2040_Connect using arduino-pico core 1.8.14-3 K Hoang 31/12/2021 Fix issue with UDP for Nano_RP2040_Connect using arduino-pico core 1.8.14-4 K Hoang 01/05/2022 Fix bugs by using some PRs from original WiFiNINA. Add WiFiMulti-related examples 1.8.14-5 K Hoang 23/05/2022 Fix bug causing data lost when sending large files 1.8.14-6 K Hoang 17/08/2022 Add support to Teensy 4.x using WiFiNINA AirLift. Fix minor bug 1.8.14-7 K Hoang 11/11/2022 Modify WiFiWebServer example to avoid crash in arduino-pico core 1.8.15-0 K Hoang 14/11/2022 Fix severe limitation to permit sending much larger data than total 4K 1.8.15-1 K Hoang 18/11/2022 Using new WiFi101_Generic library to permit sending larger data than total 4K ***********************************************************************************************************************************/ #pragma once /***************************** wl_definitions.h Created on: Mar 6, 2011 Author: dlafauci *****************************/ // Maximum size of a SSID #define WL_SSID_MAX_LENGTH 32 // Length of passphrase. Valid lengths are 8-63. #define WL_WPA_KEY_MAX_LENGTH 63 // Length of key in bytes. Valid values are 5 and 13. #define WL_WEP_KEY_MAX_LENGTH 13 // Size of a MAC-address or BSSID #define WL_MAC_ADDR_LENGTH 6 // Size of a MAC-address or BSSID #define WL_IPV4_LENGTH 4 // Maximum size of a SSID list #define WL_NETWORKS_LIST_MAXNUM 10 // Maxmium number of socket #define WIFI_MAX_SOCK_NUM 10 // Socket not available constant #define SOCK_NOT_AVAIL 255 // Default state value for WiFi state field #define NA_STATE -1 //////////////////////////////////////// typedef enum { WL_NO_SHIELD = 255, WL_NO_MODULE = WL_NO_SHIELD, WL_IDLE_STATUS = 0, WL_NO_SSID_AVAIL, WL_SCAN_COMPLETED, WL_CONNECTED, WL_CONNECT_FAILED, WL_CONNECTION_LOST, WL_DISCONNECTED, WL_AP_LISTENING, WL_AP_CONNECTED, WL_AP_FAILED } wl_status_t; //////////////////////////////////////// /* Encryption modes */ enum wl_enc_type { /* Values map to 802.11 encryption suites... */ ENC_TYPE_WEP = 5, ENC_TYPE_TKIP = 2, ENC_TYPE_CCMP = 4, /* ... except these two, 7 and 8 are reserved in 802.11-2007 */ ENC_TYPE_NONE = 7, ENC_TYPE_AUTO = 8, ENC_TYPE_UNKNOWN = 255 }; ////////////////////////////////////////
4,424
C++
.h
90
46.2
133
0.635709
khoih-prog/WiFiNINA_Generic
36
12
0
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
1,537,550
debug.h
khoih-prog_WiFiNINA_Generic/src/utility/debug.h
/********************************************************************************************************************************** debug.h - Library for Arduino WiFiNINA module/shield. Based on and modified from WiFiNINA library https://www.arduino.cc/en/Reference/WiFiNINA to support nRF52, SAMD21/SAMD51, STM32F/L/H/G/WB/MP1, Teensy, etc. boards besides Nano-33 IoT, MKRWIFI1010, MKRVIDOR400, etc. Built by Khoi Hoang https://github.com/khoih-prog/WiFiNINA_Generic Licensed under MIT license Copyright (c) 2018 Arduino SA. All rights reserved. Copyright (c) 2011-2014 Arduino LLC. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Version: 1.8.15-1 Version Modified By Date Comments ------- ----------- ---------- ----------- 1.5.0 K Hoang 27/03/2020 Initial coding to support other boards besides Nano-33 IoT, MKRWIFI1010, MKRVIDOR4000, etc. such as Arduino Mega, Teensy, SAMD21, SAMD51, STM32, etc ... 1.8.13 K Hoang 03/08/2021 Sync with WiFiNINA v1.8.13 : new FW v1.4.8. Add support to ADAFRUIT_MATRIXPORTAL_M4_EXPRESS 1.8.14-1 K Hoang 25/11/2021 Fix examples to support ATmega4809 such as UNO_WIFI_REV2 and NANO_EVERY 1.8.14-2 K Hoang 31/12/2021 Add support to Nano_RP2040_Connect using arduino-pico core 1.8.14-3 K Hoang 31/12/2021 Fix issue with UDP for Nano_RP2040_Connect using arduino-pico core 1.8.14-4 K Hoang 01/05/2022 Fix bugs by using some PRs from original WiFiNINA. Add WiFiMulti-related examples 1.8.14-5 K Hoang 23/05/2022 Fix bug causing data lost when sending large files 1.8.14-6 K Hoang 17/08/2022 Add support to Teensy 4.x using WiFiNINA AirLift. Fix minor bug 1.8.14-7 K Hoang 11/11/2022 Modify WiFiWebServer example to avoid crash in arduino-pico core 1.8.15-0 K Hoang 14/11/2022 Fix severe limitation to permit sending much larger data than total 4K 1.8.15-1 K Hoang 18/11/2022 Using new WiFi101_Generic library to permit sending larger data than total 4K ***********************************************************************************************************************************/ #pragma once #include <stdio.h> #include <string.h> //////////////////////////////////////// // KH Add, v1.6.0 #ifdef DEBUG_WIFININA_PORT #define DBG_PORT_NN DEBUG_WIFININA_PORT #else #define DBG_PORT_NN Serial #endif //////////////////////////////////////// // Change _WIFININA_LOGLEVEL_ to set tracing and logging verbosity // 0: DISABLED: no logging // 1: ERROR: errors // 2: WARN: errors and warnings // 3: INFO: errors, warnings and informational (default) // 4: DEBUG: errors, warnings, informational and debug //////////////////////////////////////// #ifndef _WIFININA_LOGLEVEL_ #define _WIFININA_LOGLEVEL_ 0 #endif /////////////////////////////////////// const char NN_MARK[] = "[NN] "; const char NN_SP[] = " "; #define NN_PRINT DBG_PORT_NN.print #define NN_PRINTLN DBG_PORT_NN.println #define NN_FLUSH DBG_PORT_NN.flush #define NN_PRINT_MARK NN_PRINT(NN_MARK) #define NN_PRINT_SP NN_PRINT(NN_SP) /////////////////////////////////////// // Error waitResponse message #define ERROR_RESPONSE ":Error waitResponse" #define NN_LOGERROR0(x) if(_WIFININA_LOGLEVEL_>0) { NN_PRINT(x); } #define NN_LOGERROR(x) if(_WIFININA_LOGLEVEL_>0) { NN_PRINT_MARK; NN_PRINTLN(x); } #define NN_LOGERROR1(x,y) if(_WIFININA_LOGLEVEL_>0) { NN_PRINT_MARK; NN_PRINT(x); NN_PRINT_SP; NN_PRINTLN(y); } #define NN_LOGERROR2(x,y,z) if(_WIFININA_LOGLEVEL_>0) { NN_PRINT_MARK; NN_PRINT(x); NN_PRINT_SP; NN_PRINT(y); NN_PRINT_SP; NN_PRINTLN(z); } #define NN_LOGERROR3(x,y,z,w) if(_WIFININA_LOGLEVEL_>0) { NN_PRINT_MARK; NN_PRINT(x); NN_PRINT_SP; NN_PRINT(y); NN_PRINT_SP; NN_PRINT(z); NN_PRINT_SP; NN_PRINTLN(w); } /////////////////////////////////////// #define NN_LOGWARN0(x) if(_WIFININA_LOGLEVEL_>1) { NN_PRINT(x); } #define NN_LOGWARN(x) if(_WIFININA_LOGLEVEL_>1) { NN_PRINT_MARK; NN_PRINTLN(x); } #define NN_LOGWARN1(x,y) if(_WIFININA_LOGLEVEL_>1) { NN_PRINT_MARK; NN_PRINT(x); NN_PRINT_SP; NN_PRINTLN(y); } #define NN_LOGWARN2(x,y,z) if(_WIFININA_LOGLEVEL_>1) { NN_PRINT_MARK; NN_PRINT(x); NN_PRINT_SP; NN_PRINT(y); NN_PRINT_SP; NN_PRINTLN(z); } #define NN_LOGWARN3(x,y,z,w) if(_WIFININA_LOGLEVEL_>1) { NN_PRINT_MARK; NN_PRINT(x); NN_PRINT_SP; NN_PRINT(y); NN_PRINT_SP; NN_PRINT(z); NN_PRINT_SP; NN_PRINTLN(w); } /////////////////////////////////////// #define NN_LOGINFO0(x) if(_WIFININA_LOGLEVEL_>2) { NN_PRINT(x); } #define NN_LOGINFO(x) if(_WIFININA_LOGLEVEL_>2) { NN_PRINT_MARK; NN_PRINTLN(x); } #define NN_LOGINFO1(x,y) if(_WIFININA_LOGLEVEL_>2) { NN_PRINT_MARK; NN_PRINT(x); NN_PRINT_SP; NN_PRINTLN(y); } #define NN_LOGINFO2(x,y,z) if(_WIFININA_LOGLEVEL_>3) { NN_PRINT_MARK; NN_PRINT(x); NN_PRINT_SP; NN_PRINT(y); NN_PRINT_SP; NN_PRINTLN(z); } #define NN_LOGINFO3(x,y,z,w) if(_WIFININA_LOGLEVEL_>3) { NN_PRINT_MARK; NN_PRINT(x); NN_PRINT_SP; NN_PRINT(y); NN_PRINT_SP; NN_PRINT(z); NN_PRINT_SP; NN_PRINTLN(w); } /////////////////////////////////////// #define NN_LOGDEBUG0(x) if(_WIFININA_LOGLEVEL_>3) { NN_PRINT(x); } #define NN_LOGDEBUG(x) if(_WIFININA_LOGLEVEL_>3) { NN_PRINT_MARK; NN_PRINTLN(x); } #define NN_LOGDEBUG1(x,y) if(_WIFININA_LOGLEVEL_>3) { NN_PRINT_MARK; NN_PRINT(x); NN_PRINT_SP; NN_PRINTLN(y); } #define NN_LOGDEBUG2(x,y,z) if(_WIFININA_LOGLEVEL_>3) { NN_PRINT_MARK; NN_PRINT(x); NN_PRINT_SP; NN_PRINT(y); NN_PRINT_SP; NN_PRINTLN(z); } #define NN_LOGDEBUG3(x,y,z,w) if(_WIFININA_LOGLEVEL_>3) { NN_PRINT_MARK; NN_PRINT(x); NN_PRINT_SP; NN_PRINT(y); NN_PRINT_SP; NN_PRINT(z); NN_PRINT_SP; NN_PRINTLN(w); } /////////////////////////////////////// #define PRINT_FILE_LINE() do { \ Serial.print("[");Serial.print(__FILE__); \ Serial.print("::");Serial.print(__LINE__);Serial.print("]");\ } while (0); //KH //#define _DEBUG_ #ifdef _DEBUG_ #define INFO(format, args...) do { \ char buf[250]; \ sprintf(buf, format, args); \ Serial.println(buf); \ } while(0); #define INFO1(x) do { PRINT_FILE_LINE() Serial.print("-I-");\ Serial.println(x); \ } while (0); #define INFO2(x,y) do { PRINT_FILE_LINE() Serial.print("-I-");\ Serial.print(x,16);Serial.print(",");Serial.println(y,16); \ } while (0); #else #define INFO1(x) do {} while(0); #define INFO2(x,y) do {} while(0); #define INFO(format, args...) do {} while(0); #endif #define WARN(args) do {} while (0); //KH #define _DEBUG_SPI_ false #if _DEBUG_SPI_ #define DBG_PIN2 5 #define DBG_PIN 4 #define START() digitalWrite(DBG_PIN2, HIGH); #define END() digitalWrite(DBG_PIN2, LOW); #define SET_TRIGGER() digitalWrite(DBG_PIN, HIGH); #define RST_TRIGGER() digitalWrite(DBG_PIN, LOW); #define INIT_TRIGGER() pinMode(DBG_PIN, OUTPUT); \ pinMode(DBG_PIN2, OUTPUT); \ RST_TRIGGER() #define TOGGLE_TRIGGER() SET_TRIGGER() \ delayMicroseconds(2); \ RST_TRIGGER() #else #define START() #define END() #define SET_TRIGGER() #define RST_TRIGGER() #define INIT_TRIGGER() #define TOGGLE_TRIGGER() #endif
7,953
C++
.h
139
54.014388
167
0.623841
khoih-prog/WiFiNINA_Generic
36
12
0
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,555
entity.cpp
FiYHer_csgo_cheats/csgo_cheats/entity.cpp
#include "config.hpp" #include "entity.h" #include "sight_trace.hpp" bool entity_class::is_enemy() noexcept { return g_config.memory.is_other_enemy(this, g_config.entity_list->get_entity(g_config.engine->get_local_player())); } bool entity_class::is_visiable(const self_vector_struct& position) noexcept { static sight_trace_struct sight_trace; //获取自己 auto local_player = g_config.entity_list->get_entity(g_config.engine->get_local_player()); if (!local_player) return false; //获取自己看敌人位置的状态 g_config.engine_trace->trace_ray({ local_player->get_eye_position(),position }, 0x46004009, { local_player }, sight_trace); return sight_trace.entity == this || sight_trace.fraction > 0.97f; } self_vector_struct entity_class::get_eye_position() noexcept { self_vector_struct ret; call_virtual_method<void, self_vector_struct&>(this, 284, ret); return ret; } self_vector_struct entity_class::get_bone_position(int bone) noexcept { matrix3x4_class head_matrix[128]; setup_bones(head_matrix, 128, 256, 0.0f); return self_vector_struct{ head_matrix[bone][0][3], head_matrix[bone][1][3], head_matrix[bone][2][3] }; } constexpr bool entity_class::setup_bones(matrix3x4_class* out, int max_bones, int bone_mask, float current_time) noexcept { return call_virtual_method<bool, matrix3x4_class*, int, int, float>(this + 4, 13, out, max_bones, bone_mask, current_time); }
1,392
C++
.cpp
33
40
124
0.749813
FiYHer/csgo_cheats
35
18
4
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,556
net_vars.cpp
FiYHer_csgo_cheats/csgo_cheats/net_vars.cpp
#include "net_vars.h" #include "config.hpp" net_vars_class::net_vars_class() noexcept { for (auto clientClass = g_config.client->get_all_classes(); clientClass; clientClass = clientClass->next) walk_table(false, clientClass->network_name, clientClass->recv_table); } void net_vars_class::restore() noexcept { } uint16_t net_vars_class::operator[](const uint32_t hash) noexcept { return offsets[hash]; } void net_vars_class::walk_table(bool unload, const char* networkName, recv_table_struct* recvTable, const std::size_t offset) noexcept { for (int i = 0; i < recvTable->propCount; ++i) { //获取数据 auto& prop = recvTable->props[i]; //十进制判断 if (isdigit(prop.name[0])) continue; //哈希的判断 if (fnv_struct::hash_runtime(prop.name) == fnv_struct::hash("baseclass")) continue; //递归 if (prop.type == 6 && prop.dataTable && prop.dataTable->netTableName[0] == 'D') walk_table(unload, networkName, prop.dataTable, prop.offset + offset); //获取hash const auto hash{ fnv_struct::hash_runtime((networkName + std::string{ "->" } +prop.name).c_str()) }; //没有加载 if (!unload) offsets[hash] = uint16_t(offset + prop.offset); } }
1,180
C++
.cpp
35
30.6
134
0.70297
FiYHer/csgo_cheats
35
18
4
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,557
main.cpp
FiYHer_csgo_cheats/csgo_cheats/main.cpp
#include "config.hpp" #include "hooks.hpp" #include "imgui_gui.hpp" //隐藏自身类 class hide_self { public: hide_self(void* module) { void* pPEB = nullptr; //读取PEB指针 _asm { push eax mov eax, fs:[0x30] mov pPEB, eax pop eax } //操作得到保存全部模块的双向链表头指针 void* pLDR = *((void**)((unsigned char*)pPEB + 0xc)); void* pCurrent = *((void**)((unsigned char*)pLDR + 0x0c)); void* pNext = pCurrent; //对链表进行遍历,对指定模块进行断链隐藏 do { void* pNextPoint = *((void**)((unsigned char*)pNext)); void* pLastPoint = *((void**)((unsigned char*)pNext + 0x4)); void* nBaseAddress = *((void**)((unsigned char*)pNext + 0x18)); if (nBaseAddress == module) { *((void**)((unsigned char*)pLastPoint)) = pNextPoint; *((void**)((unsigned char*)pNextPoint + 0x4)) = pLastPoint; pCurrent = pNextPoint; } pNext = *((void**)pNext); } while (pCurrent != pNext); } }; const hide_self hide{ GetModuleHandleW(NULL) }; configuration_struct g_config;//配置文件 net_vars_class g_net_vars;//玩家信息辅助 imgui_gui_class g_imgui;//界面显示 hooks_class g_hooks;//游戏流程劫持 //---注意初始化的顺序,不然会出现各式各样的错误---//
1,194
C++
.cpp
44
22.295455
66
0.654028
FiYHer/csgo_cheats
35
18
4
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,558
global_var.cpp
FiYHer_csgo_cheats/csgo_cheats/global_var.cpp
#include "global_vars.h" #include "config.hpp" float global_vars_struct::serverTime(user_cmd_struct* cmd /*= nullptr*/) noexcept { static int last_tick; static user_cmd_struct* last_cmd; if (cmd) { if (!last_cmd || last_cmd->has_been_predicted) last_tick = g_config.entity_list->get_entity(g_config.engine->get_local_player())->get_tick_base(); else last_tick++; last_cmd = cmd; } return last_tick * interval_per_tick; }
436
C++
.cpp
14
29.071429
148
0.713604
FiYHer/csgo_cheats
35
18
4
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,565
node.hpp
FiYHer_csgo_cheats/csgo_cheats/node.hpp
#pragma once //节点模板结构 template <typename Key, typename Value> struct node_struct { int previousId;//上一个id int nextId;//下一个id void* _unknownPtr;//未知指针 int _unknown;//未知值 Key key; Value value; };
219
C++
.h
12
15.166667
39
0.760638
FiYHer/csgo_cheats
35
18
4
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,566
move_type.hpp
FiYHer_csgo_cheats/csgo_cheats/move_type.hpp
#pragma once enum class move_type_enum { NOCLIP = 8, LADDER = 9 };
70
C++
.h
6
10.166667
26
0.703125
FiYHer/csgo_cheats
35
18
4
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,567
recv_proxy_data.hpp
FiYHer_csgo_cheats/csgo_cheats/recv_proxy_data.hpp
#pragma once #include "self_vector.hpp" //结构数据结构 typedef struct recv_proxy_data_struct { int pad; union { float _float; long _int; char* _string; void* data; self_vector_struct vector; int64_t int64; } value; }recv_proxy_data_struct; using recv_proxy = std::add_pointer_t<void(recv_proxy_data_struct&, void*, void*)>;
343
C++
.h
17
17.705882
83
0.72327
FiYHer/csgo_cheats
35
18
4
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,568
sight_trace_filter.hpp
FiYHer_csgo_cheats/csgo_cheats/sight_trace_filter.hpp
#pragma once #include "entity.h" typedef struct trace_filter_struct { trace_filter_struct(const entity_class* entity) : skip{ entity } { } virtual bool should_hit_entity(entity_class* entity, int) { return entity != skip; } virtual int get_trace_type() const { return 0; } const void* skip; }trace_filter_struct;
317
C++
.h
9
33.777778
85
0.743506
FiYHer/csgo_cheats
35
18
4
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,569
class_id.hpp
FiYHer_csgo_cheats/csgo_cheats/class_id.hpp
#pragma once //对应类ID enum class classId_enum { BaseCSGrenadeProjectile = 9,//炸弹 BreachChargeProjectile = 29,//炸弹 BumpMineProjectile = 33,//炸弹 C4,//炸弹包 Chicken = 36,//鸡 CSPlayer = 40,//玩家 CSRagdoll = 42,//布娃娃 Deagle = 46, DecoyProjectile = 48,//诱饵弹 Drone,//无人驾驶飞机 Dronegun,//无人机枪 EconEntity = 53, EconWearable, Hostage = 97, Healthshot = 104, Cash, Knife = 107, KnifeGG, MolotovProjectile = 113, AmmoBox = 124, LootCrate, RadarJammer, WeaponUpgrade, PlantedC4, PropDoorRotating = 142, SensorGrenadeProjectile = 152, SmokeGrenadeProjectile = 156, SnowballProjectile = 160, Tablet = 171, Aug = 231, Awp, Elite = 238, FiveSeven = 240, G3sg1, Glock = 244, P2000, P250 = 257, Scar20 = 260, Sg553 = 264, Ssg08 = 266, Tec9 = 268 };
798
C++
.h
46
14.73913
33
0.726768
FiYHer/csgo_cheats
35
18
4
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,570
aim.hpp
FiYHer_csgo_cheats/csgo_cheats/aim.hpp
#pragma once #include "config.hpp" #include "user_cmd.hpp" //自瞄命名空间 namespace aim_space { /* ////计算相对角度 //self_vector_struct calculate_relative_angle(const self_vector_struct& source, const self_vector_struct& destination, const self_vector_struct& viewAngles) noexcept //{ // constexpr auto radiansToDegrees = [](float radians) constexpr noexcept { return radians * 180.0f / static_cast<float>(3.14159265358979323846); }; // self_vector_struct delta = destination - source; // self_vector_struct angles{ radiansToDegrees(atan2f(-delta.z, std::hypotf(delta.x, delta.y))) - viewAngles.x, radiansToDegrees(atan2f(delta.y, delta.x)) - viewAngles.y }; // angles.normalize(); // return angles; //} ////开始自瞄 //void run(user_cmd_struct* cmd) //{ // //获取自身信息 // const auto local_player = g_config.entity_list->get_entity(g_config.engine->get_local_player()); // if (!local_player || local_player->get_next_attack() > g_config.global_vars->serverTime()) return; // //获取当前武器信息 // const auto active_weapon = local_player->get_active_weapon(); // if (!active_weapon || !active_weapon->is_clip()) return; // if (g_config.control.aim_enable //开启了自瞄 // && (cmd->buttons & user_cmd_struct::IN_ATTACK//有射击命令 // || g_config.control.aim_auto_shot //自动开枪 // || g_config.control.aim_aimlock) //开启了一直锁定敌人 // && active_weapon->get_inaccuracy() <= g_config.control.aim_max_aim_inaccuracy)//当前枪械的不正确率在允许范围内 // { // //获取允许自瞄范围 // auto best_fov = g_config.control.aim_fov; // //最好瞄准的敌人位置 // self_vector_struct best_target{}; // //获取我们的视线范围 // auto local_layer_eye_position = local_player->get_eye_position(); // //获取自瞄punch // auto aim_punch = local_player->get_aim_punch(); // //遍历每一个玩家 // for (int i = 1; i <= g_config.engine->get_max_clients(); i++) // { // //获取玩家信息 // auto entity = g_config.entity_list->get_entity(i); // if (!entity || entity == local_player || entity->is_dormant() || !entity->is_alive() || !entity->is_enemy() || entity->is_gun_game_immunity()) continue; // //获取头部骨骼的位置 // auto head_position = entity->get_bone_position(g_config.control.aim_bone); // //如果不可见 // if(!entity->is_visiable(head_position)) continue; // //计算相对角度 // auto angle = calculate_relative_angle(local_layer_eye_position, head_position, cmd->view_angles); // //计算视角 // auto fov = std::hypotf(angle.x, angle.y); // //如果在范围内 // if (fov < best_fov) // { // best_fov = fov; // best_target = head_position; // break; // } // } // //有目标了 // if (best_target) // { // //计算角度 // auto angle = calculate_relative_angle(local_player->get_eye_position(), best_target, cmd->view_angles + aim_punch); // // // bool clamped = false; // if (fabs(angle.x) > 255.0f || fabs(angle.y) > 255.0f) // { // angle.x = std::clamp(angle.x, -255.0f, 255.0f); // angle.y = std::clamp(angle.y, -255.0f, 255.0f); // clamped = true; // } // //设置角度 // cmd->view_angles += angle; // g_config.engine->set_view_angles(cmd->view_angles); // //自瞄开镜 // if (g_config.control.aim_auto_scope && active_weapon->get_next_primary_attack() <= g_config.global_vars->serverTime() && active_weapon->is_sniper_rifle() && !local_player->get_is_scoped()) // cmd->buttons |= user_cmd_struct::IN_ATTACK2; // //自动开枪 // if (g_config.control.aim_auto_shot && active_weapon->get_next_primary_attack() <= g_config.global_vars->serverTime() && !clamped && active_weapon->get_inaccuracy() <= g_config.control.aim_max_shot_inaccuracy) // cmd->buttons |= user_cmd_struct::IN_ATTACK; // //取消开枪 // if (clamped) cmd->buttons &= ~user_cmd_struct::IN_ATTACK; // } // } //} */ //自瞄角度 self_vector_struct aim_angle(user_cmd_struct* cmd, self_vector_struct& local_pos,self_vector_struct& enemy_pos) { float x = local_pos.x - enemy_pos.x; float y = local_pos.y - enemy_pos.y; float z = local_pos.z - enemy_pos.z + 60.0f + 5.0f + g_config.control.aim_offset; if (cmd->buttons & user_cmd_struct::IN_DUCK) z -= 15.0f; static const float pi = 3.1415f; self_vector_struct angle{ atan(z / sqrt(x * x + y * y)) / pi * 180.f,atan(y / x) ,0 }; if (x >= 0.0f && y >= 0.0f) angle.y = angle.y / pi * 180.0f - 180.0f; else if (x < 0.0f && y >= 0.0f) angle.y = angle.y / pi * 180.0f; else if (x < 0.0f && y < 0.0f) angle.y = angle.y / pi * 180.0f; else if (x >= 0.0f && y < 0.0f) angle.y = angle.y / pi * 180.f + 180.0f; return angle; } //计算自瞄距离 float aim_distance(self_vector_struct& enemy_pos) { self_vector_struct origin_pos; g_config.engine->get_view_angles(origin_pos); float width = abs(origin_pos.x - enemy_pos.x); float height = abs(origin_pos.y - enemy_pos.y); return std::hypot(width, height); } //开启自瞄 void run(user_cmd_struct* cmd) noexcept { //没有开启自瞄 if (!g_config.control.aim_enable) return; if (cmd->buttons & user_cmd_struct::IN_ATTACK//开枪状态 || g_config.control.aim_auto_shot//自动射击 || g_config.control.aim_auto_scope//自动开镜 || g_config.control.aim_aimlock)//敌人锁定 { //获取自己 const auto local_player = g_config.entity_list->get_entity(g_config.engine->get_local_player()); if (!local_player || !local_player->is_alive() || local_player->get_next_attack() > g_config.global_vars->serverTime()) return; //获取武器 const auto active_weapon = local_player->get_active_weapon(); if (!active_weapon || !active_weapon->is_clip()) return; //武器的不准确率超过了我们允许的范围 if (active_weapon->get_inaccuracy() > g_config.control.aim_max_aim_inaccuracy) return; //最近玩家位置 float distance = g_config.control.aim_fov; self_vector_struct angle{}; //遍历玩家 for (int i = 1; i <= g_config.engine->get_max_clients(); i++) { //获取玩家对象 auto entity = g_config.entity_list->get_entity(i); if (!entity || entity == local_player || !entity->is_alive() || !entity->is_enemy() || entity->is_dormant() || entity->is_gun_game_immunity()) continue; //获取敌人位置 int bone = g_config.control.aim_bone; //敌人身体部位 std::vector<int> bones = (bone == -1) ? std::vector<int>{ 8, 7, 6, 5, 4, 3 } : std::vector<int>{ bone }; //判断哪一个部位最近 for (const auto& it : bones) { //获取该部位 self_vector_struct enemy_pos = entity->get_bone_position(it); //如果玩家被墙体挡住了 if (!entity->is_visiable(enemy_pos)) continue; //获取自瞄角度 self_vector_struct temp_angle = aim_angle(cmd, local_player->get_origin(), enemy_pos); float temp_distance = aim_distance(temp_angle); if (temp_distance < distance) { distance = temp_distance; angle = temp_angle; } } } //可以自瞄 if (angle) { //设置自瞄角度 cmd->view_angles = angle; g_config.engine->set_view_angles(cmd->view_angles); //自动开镜 if (g_config.control.aim_auto_scope && active_weapon->get_next_primary_attack() <= g_config.global_vars->serverTime() && active_weapon->is_sniper_rifle() && !local_player->get_is_scoped()) cmd->buttons |= user_cmd_struct::IN_ATTACK2; //自动开枪 if (g_config.control.aim_auto_shot && active_weapon->get_next_primary_attack() <= g_config.global_vars->serverTime() && active_weapon->get_inaccuracy() <= g_config.control.aim_max_shot_inaccuracy) cmd->buttons |= user_cmd_struct::IN_ATTACK; } } } }
7,548
C++
.h
177
37.757062
214
0.64495
FiYHer/csgo_cheats
35
18
4
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,571
engine.hpp
FiYHer_csgo_cheats/csgo_cheats/engine.hpp
#pragma once #include "help_func.hpp" #include "player_info.hpp" #include "self_vector.hpp" //游戏引擎类 class engine_class { public: //获取本地玩家信息 constexpr auto get_local_player() noexcept { return call_virtual_method<int>(this, 12); } //判断是否在游戏中 constexpr auto is_in_game() noexcept { return call_virtual_method<bool>(this, 26); } //获取指定索引得人物信息 constexpr auto get_player_info(int entityIndex, const player_info_struct& playerInfo) noexcept { return call_virtual_method<bool, int, const player_info_struct&>(this, 8, entityIndex, playerInfo); } //根据用户ID获取玩家 constexpr auto get_player_for_user_id(int userId) noexcept { return call_virtual_method<int, int>(this, 9, userId); } //获取全部游戏玩家数量 constexpr auto get_max_clients() noexcept { return call_virtual_method<int>(this, 20); } //获取自身矩阵 using self_matrix = float[4][4]; constexpr auto world_to_screen_matrix() noexcept { return call_virtual_method<const self_matrix&>(this, 37); } //获取人物角度 constexpr auto get_view_angles(self_vector_struct& angles) noexcept { call_virtual_method<void, self_vector_struct&>(this, 18, angles); } //设置人物角度 constexpr auto set_view_angles(const self_vector_struct& angles) noexcept { call_virtual_method<void, const self_vector_struct&>(this, 19, angles); } };
1,360
C++
.h
50
23.68
101
0.750203
FiYHer/csgo_cheats
35
18
4
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,572
localize.hpp
FiYHer_csgo_cheats/csgo_cheats/localize.hpp
#pragma once #include "help_func.hpp" // class localize_class { public: // constexpr auto find(const char* tokenName) noexcept { return call_virtual_method<wchar_t*, const char*>(this, 12, tokenName); } };
212
C++
.h
12
16.166667
73
0.74
FiYHer/csgo_cheats
35
18
4
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,573
glow_object_manager.hpp
FiYHer_csgo_cheats/csgo_cheats/glow_object_manager.hpp
#pragma once #include "utl_vector.hpp" #include "glow_object_definition.hpp" //辉光对象管理器结构 typedef struct glow_object_mamager_struct { //辉光定义列表 utl_vector_class<glow_object_definition_struct> glow_object_definitions; int firstFreeSlot; //注销辉光对象 constexpr void un_register_glow_object(int index) noexcept { glow_object_definitions[index].nextFreeSlot = firstFreeSlot; glow_object_definitions[index].entity = nullptr; glow_object_definitions[index].renderWhenOccluded = false; glow_object_definitions[index].renderWhenUnoccluded = false; firstFreeSlot = index; } }glow_object_mamager_struct;
629
C++
.h
19
29.947368
73
0.807167
FiYHer/csgo_cheats
35
18
4
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,574
recv_prop.hpp
FiYHer_csgo_cheats/csgo_cheats/recv_prop.hpp
#pragma once #include "recv_proxy_data.hpp" typedef struct recv_prop_struct { char* name; int type; int flags; int stringBufferSize; int insideArray; const void* extraData; recv_prop_struct* arrayProp; void* arrayLengthProxy; recv_proxy proxy; void* dataTableProxy; struct recv_table_struct* dataTable; int offset; int elementStride; int elementCount; const char* parentArrayPropName; }recv_prop_struct;
420
C++
.h
20
19.2
37
0.8025
FiYHer/csgo_cheats
35
18
4
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,575
frame_state.hpp
FiYHer_csgo_cheats/csgo_cheats/frame_state.hpp
#pragma once //сно╥ж║в╢л╛ enum class frame_stage_enum { UNDEFINED = -1, START, NET_UPDATE_START, NET_UPDATE_POSTDATAUPDATE_START, NET_UPDATE_POSTDATAUPDATE_END, NET_UPDATE_END, RENDER_START, RENDER_END };
214
C++
.h
13
14.769231
33
0.77
FiYHer/csgo_cheats
35
18
4
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,576
entity_list.hpp
FiYHer_csgo_cheats/csgo_cheats/entity_list.hpp
#pragma once #include "help_func.hpp" #include "entity.h" //实例列表类 class entity_list_class { public: //获取指定索引实例 constexpr auto get_entity(int index) noexcept { return call_virtual_method<entity_class*, int>(this, 3, index); } //根据句柄获取实例 constexpr auto get_entity_from_handle(int handle) noexcept { return call_virtual_method<entity_class*, int>(this, 4, handle); } };
401
C++
.h
18
19.388889
66
0.750693
FiYHer/csgo_cheats
35
18
4
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,577
sight_trace.hpp
FiYHer_csgo_cheats/csgo_cheats/sight_trace.hpp
#pragma once #include "self_vector.hpp" #include "entity.h" //玩家视线跟踪 typedef struct sight_trace_struct { self_vector_struct start_pos;//开始位置 self_vector_struct end_pos;//结束位置 std::byte pad[20];//未知数据 float fraction; int contents; unsigned short disp_flags; bool all_solid; bool start_solid; std::byte pad1[4]; struct _surface_struct { const char* name; short surface_props; unsigned short flags; } surface_struct; int hit_group; std::byte pad2[4]; entity_class* entity; int hit_box; }sight_trace_struct;
544
C++
.h
26
18.384615
36
0.756
FiYHer/csgo_cheats
35
18
4
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,578
self_string.hpp
FiYHer_csgo_cheats/csgo_cheats/self_string.hpp
#pragma once //辅助字符串结构 typedef struct self_string_struct { char* buffer;//内容 int capacity;//申请了大小 int growSize;//增长大小 int length;//长度 }self_string_struct;
179
C++
.h
9
16.222222
33
0.773333
FiYHer/csgo_cheats
35
18
4
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,579
client_class.hpp
FiYHer_csgo_cheats/csgo_cheats/client_class.hpp
#pragma once #include <windows.h> #include <type_traits> #include "rect_table.hpp" #include "class_id.hpp" class entity_class; //客户类结构 typedef struct client_class_struct { std::add_pointer_t<entity_class* __cdecl(int, int)> createFunction;//手套更换需要 void* create_event_function;//创建事件函数 char* network_name;//网络名称 recv_table_struct* recv_table;// client_class_struct* next; classId_enum classId; }client_class_struct;
444
C++
.h
16
24.9375
76
0.77284
FiYHer/csgo_cheats
35
18
4
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,580
weapon_info.hpp
FiYHer_csgo_cheats/csgo_cheats/weapon_info.hpp
#pragma once #include "weapon_item_definition_index.hpp" // 武器信息 typedef struct weapon_info_struct { constexpr weapon_info_struct(const char* model, const char* icon = nullptr) : model(model), icon(icon) {} const char* model;//模型字符串 const char* icon;//图标字符串 }weapon_info_struct;
302
C++
.h
11
24.363636
78
0.756364
FiYHer/csgo_cheats
35
18
4
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,581
game_event.hpp
FiYHer_csgo_cheats/csgo_cheats/game_event.hpp
#pragma once #include "help_func.hpp" //游戏事件类 class game_event_class { public: //获取整型数据 constexpr auto get_int(const char* keyName) noexcept { return call_virtual_method<int, const char*, int>(this, 6, keyName, 0); } //获取字符串数据 constexpr auto get_string(const char* keyName) noexcept { return call_virtual_method<const char*, const char*, const char*>(this, 9, keyName, ""); } //设置字符串数据 constexpr auto set_string(const char* keyName, const char* value) noexcept { call_virtual_method<void, const char*, const char*>(this, 16, keyName, value); } };
592
C++
.h
22
23.863636
90
0.731123
FiYHer/csgo_cheats
35
18
4
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,582
report.hpp
FiYHer_csgo_cheats/csgo_cheats/report.hpp
#pragma once #include "config.hpp" //举报命名空间 namespace report_space { //举报列表 static std::vector<uint64_t> report_players_list; //清空举报玩家列表 void clear_report_list() noexcept { report_players_list.clear(); } //获取当前房间玩家信息 void get_room_players_info() noexcept { //获取本地玩家 const auto local_player = g_config.entity_list->get_entity(g_config.engine->get_local_player()); if (!local_player) return; //清空原本信息 g_config.control.report_players.clear(); //遍历玩家 for (int i = 1; i < g_config.engine->get_max_clients(); i++) { //获取玩家 auto entity = g_config.entity_list->get_entity(i); if (!entity || entity == local_player) continue; //获取玩家信息 player_info_struct player_info; if (!g_config.engine->get_player_info(i, player_info) || player_info.fakeplayer) continue; //加入列表 g_config.control.report_players.push_back(std::move(player_info)); } } //举报单个玩家 void report_player(const std::string& report_text, uint64_t player_xuid) noexcept { //举报玩家 g_config.memory.submit_report(std::to_string(player_xuid).c_str(), report_text.c_str()); } //举报全部玩家 void report_players(const std::string& report_text) noexcept { for (const auto& it : g_config.control.report_players) { //如果举报过了的 if (std::find(report_players_list.cbegin(), report_players_list.cend(), it.xuid) != report_players_list.cend()) continue; //举报玩家 g_config.memory.submit_report(std::to_string(it.xuid).c_str(), report_text.c_str()); //加入列表 report_players_list.push_back(it.xuid); //防止举报过多 break; } } //开始举报 void run() noexcept { //没开 if (!g_config.control.report_enable) return; //获取所有玩家 get_room_players_info(); //上一次举报时间,防止举报太多而卡出房间 static float last_report_time = 0.0f; if (last_report_time + g_config.control.report_interval > g_config.global_vars->real_time) return; //举报信息 std::string report_info; if (g_config.control.report_text_abuse) report_info += "textabuse,"; if (g_config.control.report_grief) report_info += "grief,"; if (g_config.control.report_wall_hack) report_info += "wallhack,"; if (g_config.control.report_aim_bot) report_info += "aimbot,"; if (g_config.control.report_speed_hack) report_info += "speedhack,"; if (report_info.empty()) return; //开始举报 if (g_config.control.report_mode == 1) report_players(report_info); else report_player(report_info, g_config.control.report_player_xuid); //更新时间 last_report_time = g_config.global_vars->real_time; } }
2,608
C++
.h
79
28.265823
124
0.703751
FiYHer/csgo_cheats
35
18
4
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,584
cvar.hpp
FiYHer_csgo_cheats/csgo_cheats/cvar.hpp
#pragma once #include "con_var.hpp" class cvar_class { public: //查找指定值 constexpr auto findVar(const char* name) noexcept { return call_virtual_method<con_var_struct*, const char*>(this, 15, name); } };
215
C++
.h
11
17.363636
75
0.737374
FiYHer/csgo_cheats
35
18
4
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,585
weapen_item_schema.hpp
FiYHer_csgo_cheats/csgo_cheats/weapen_item_schema.hpp
#pragma once #include <cstddef> #include "head.hpp" #include "paint_kit.hpp" //ÎäÆ÷Ƥ·ôÏîÄ¿ class weapen_item_schema_class { private: void* vmt; std::byte pad[0x28C]; public: head_struct<int, paint_kit_struct*> paintKits; };
231
C++
.h
13
16.307692
47
0.748837
FiYHer/csgo_cheats
35
18
4
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,586
global_vars.h
FiYHer_csgo_cheats/csgo_cheats/global_vars.h
#pragma once #include <cstddef> #include "user_cmd.hpp" //全局的内存变量信息 typedef struct global_vars_struct { const float real_time;//实时时间 const int frame_count; const float absolute_frame_time; const std::byte pad[4]; float current_time; float frame_time; const int max_clients; const int tick_count; const float interval_per_tick; float serverTime(user_cmd_struct* cmd = nullptr) noexcept; }global_vars_struct;
434
C++
.h
17
22.941176
59
0.783042
FiYHer/csgo_cheats
35
18
4
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,588
player_info.hpp
FiYHer_csgo_cheats/csgo_cheats/player_info.hpp
#pragma once #include <stdint.h> //Íæ¼ÒÐÅÏ¢ typedef struct player_info_struct { uint64_t version; union { uint64_t xuid; struct { uint32_t xuidLow; uint32_t xuidHigh; }; }; char name[128]; int userId; char guid[33]; uint32_t friendsId; char friendsName[128]; bool fakeplayer; bool hltv; int customfiles[4]; unsigned char filesdownloaded; int entityIndex; }player_info_struct;
406
C++
.h
26
13.461538
33
0.744737
FiYHer/csgo_cheats
35
18
4
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,589
weapen_kit.hpp
FiYHer_csgo_cheats/csgo_cheats/weapen_kit.hpp
#pragma once #include <string> //ÎäÆ÷Ƥ·ô½á¹¹ typedef struct weapen_kit_struct { weapen_kit_struct(int id, std::string&& name) noexcept : id(id), name(name) { } int id; std::string name; auto operator<(const weapen_kit_struct& other) const noexcept { return name < other.name; } }weapen_kit_struct;
309
C++
.h
13
22
80
0.731293
FiYHer/csgo_cheats
35
18
4
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,590
fnv.hpp
FiYHer_csgo_cheats/csgo_cheats/fnv.hpp
#pragma once #include <stdint.h> //哈希获取结构 typedef struct fnv_struct { #define offsetBasis 0x811c9dc5 #define prime 0x1000193 static uint32_t hash(const char* str, const uint32_t value = offsetBasis) noexcept { return *str ? hash(str + 1, (value ^ *str) * static_cast<unsigned long long>(prime)) : value; } static uint32_t hash_runtime(const char* str) noexcept { auto value = offsetBasis; while (*str) { value ^= *str++; value *= prime; } return value; } }fnv_struct;
503
C++
.h
22
20.318182
95
0.711253
FiYHer/csgo_cheats
35
18
4
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,591
engine_sight_trace.hpp
FiYHer_csgo_cheats/csgo_cheats/engine_sight_trace.hpp
#pragma once #include "ray.hpp" #include "sight_trace_filter.hpp" #include "sight_trace.hpp" class engine_trace_class { public: constexpr auto get_point_contents(const self_vector_struct& absPosition, int contentsMask) noexcept { return call_virtual_method<int, const self_vector_struct&, int, entity_class*>(this, 0, absPosition, contentsMask, nullptr); } constexpr void trace_ray(const ray_struct& ray, unsigned int mask, const trace_filter_struct& filter, sight_trace_struct& trace) noexcept { call_virtual_method<void, const ray_struct&, unsigned int, const trace_filter_struct&, sight_trace_struct&>(this, 5, ray, mask, filter, trace); } };
658
C++
.h
16
39.375
145
0.770313
FiYHer/csgo_cheats
35
18
4
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,592
hooks.hpp
FiYHer_csgo_cheats/csgo_cheats/hooks.hpp
#pragma once #include "config.hpp" #include "skin.hpp" #include "aim.hpp" #include "report.hpp" #include "imgui_gui.hpp" #include "glow.hpp" #include "other.hpp" #include <assert.h> #include <Psapi.h> #include <xmmintrin.h> #include <pmmintrin.h> #include <d3d9.h> #pragma comment(lib,"d3d9") //前向声明 static LRESULT __stdcall my_window_proc(HWND window, UINT msg, WPARAM wParam, LPARAM lParam) noexcept; static HRESULT __stdcall my_present(IDirect3DDevice9* device, const RECT* src, const RECT* dest, HWND windowOverride, const RGNDATA* dirtyRegion) noexcept; static HRESULT __stdcall my_reset(IDirect3DDevice9* device, D3DPRESENT_PARAMETERS* params) noexcept; static int __stdcall do_post_screen_effects(int param) noexcept; static void __stdcall frame_stage_notify(frame_stage_enum stage) noexcept; static bool __stdcall create_move(float input_sample_time, user_cmd_struct* cmd) noexcept; //钩子类 class hooks_class { public: //虚拟内存钩子类 class vmt_class { private: void* m_base;//内存基址 uintptr_t* m_old_vmt;//原始的地址 uintptr_t* m_new_vmt;//新的地址 size_t m_length;//地址页面长度 //计算有效页面数量 size_t get_use_memory_length(uintptr_t* vmt) noexcept { size_t length = 0; //获取该地址的页面信息,该页面能读取能执行 MEMORY_BASIC_INFORMATION memoryInfo; while (VirtualQuery(LPCVOID(vmt[length]), &memoryInfo, sizeof(memoryInfo)) && memoryInfo.Protect == PAGE_EXECUTE_READ) length++; return length; } //查找可用的空闲内存地址页面 uintptr_t* get_free_memory_page(void* const base, int length) noexcept { //获取内存相关信息 MEMORY_BASIC_INFORMATION mbi; VirtualQuery(base, &mbi, sizeof(mbi)); //获取模块信息 MODULEINFO moduleInfo; GetModuleInformation(GetCurrentProcess(), static_cast<HMODULE>(mbi.AllocationBase), &moduleInfo, sizeof(moduleInfo)); //取得模块结束地址 auto moduleEnd{ reinterpret_cast<uintptr_t*>(static_cast<std::byte*>(moduleInfo.lpBaseOfDll) + moduleInfo.SizeOfImage) }; for (auto currentAddress = moduleEnd - length; currentAddress > moduleInfo.lpBaseOfDll; currentAddress -= *currentAddress ? length : 1) if (!*currentAddress)//地址有效 if (VirtualQuery(currentAddress, &mbi, sizeof(mbi)) && mbi.State == MEM_COMMIT//内存地址预定了 && mbi.Protect == PAGE_READWRITE && mbi.RegionSize >= length * sizeof(uintptr_t)//能读能写 && std::all_of(currentAddress, currentAddress + length, [](uintptr_t a) { return !a; })) return currentAddress; return nullptr; } public: vmt_class(void* const base) noexcept { //保证传进来的内存基址不为空 assert(base); //保存内存基址 m_base = base; //获取原始页面地址 m_old_vmt = *reinterpret_cast<uintptr_t**>(base); //获取可用页面数量 m_length = get_use_memory_length(m_old_vmt) + 1; //获取新的可用页面地址 m_new_vmt = get_free_memory_page(base, m_length); assert(m_new_vmt); //将原始内存页面的数据全部复制到新的内存页面 std::copy(m_old_vmt - 1, m_old_vmt - 1 + m_length, m_new_vmt); //用新内存页面覆盖原始内存页面 *reinterpret_cast<uintptr_t**>(base) = m_new_vmt + 1; } //恢复原始地址 void restore() noexcept { //还原地址 if (m_base && m_old_vmt) *reinterpret_cast<uintptr_t**>(m_base) = m_old_vmt; //清空相关内存 if (m_new_vmt) ZeroMemory(m_new_vmt, m_length * sizeof(uintptr_t)); } //用指定函数地址覆盖指定内存页面的地址 template<typename T> void hook_at(size_t index, T fun) const noexcept { if (index <= m_length) m_new_vmt[index + 1] = reinterpret_cast<uintptr_t>(fun); } //调用原始页面地址 template<typename T, std::size_t Idx, typename ...Args> constexpr auto call_original(Args... args) const noexcept { return reinterpret_cast<T(__thiscall*)(void*, Args...)>(m_old_vmt[Idx])(m_base, args...); } //获取原始页面地址 template<typename T, typename ...Args> constexpr auto get_original(size_t index, Args... args) const noexcept { return reinterpret_cast<T(__thiscall*)(void*, Args...)>(m_old_vmt[index]); } }; public: hooks_class() noexcept { srand((unsigned int)time(0)); //武器皮肤初始化 skin_space::initialize_skin(); skin_space::initialize_weapon(); skin_space::initialize_knife(); _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON); _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON); //替换游戏窗口过程 original_window_proc = WNDPROC(SetWindowLongPtrA(FindWindowW(L"Valve001", nullptr), GWLP_WNDPROC, LONG_PTR(my_window_proc))); //替换present和reset函数 original_present = **reinterpret_cast<decltype(original_present)**>(g_config.memory.present); **reinterpret_cast<decltype(my_present)***>(g_config.memory.present) = my_present; original_reset = **reinterpret_cast<decltype(original_reset)**>(g_config.memory.reset); **reinterpret_cast<decltype(my_reset)***>(g_config.memory.reset) = my_reset; client.hook_at(37, frame_stage_notify); clientMode.hook_at(24, create_move); clientMode.hook_at(44, do_post_screen_effects); //g_config.gmae_ui->message_box("good message", "csgo helper inject finish"); } //恢复游戏原数据 void restore() noexcept { clientMode.restore(); client.restore(); glow_space::clear_custom_objects(); SetWindowLongPtrA(FindWindowW(L"Valve001", nullptr), GWLP_WNDPROC, LONG_PTR(original_window_proc)); **reinterpret_cast<void***>(g_config.memory.present) = original_present; **reinterpret_cast<void***>(g_config.memory.reset) = original_reset; } vmt_class clientMode{ g_config.client_mode };//客户模式hook vmt_class client{ g_config.client };//客户端hook //原始游戏窗口过程 WNDPROC original_window_proc; //Present std::add_pointer_t<HRESULT __stdcall(IDirect3DDevice9*, const RECT*, const RECT*, HWND, const RGNDATA*)> original_present; //Reset std::add_pointer_t<HRESULT __stdcall(IDirect3DDevice9*, D3DPRESENT_PARAMETERS*)> original_reset; }; extern hooks_class g_hooks; //我们准备的窗口过程 static LRESULT __stdcall my_window_proc(HWND window, UINT msg, WPARAM wParam, LPARAM lParam) noexcept { //声明imgui里面的窗口过程 LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); //进入imgui里面进行消息处理 ImGui_ImplWin32_WndProcHandler(window, msg, wParam, lParam); //控制imgui的显示和隐藏 if (msg == WM_KEYDOWN) { if(wParam == VK_INSERT) g_config.control.show_imgui = !g_config.control.show_imgui; if (wParam == VK_DOWN || wParam == VK_RIGHT || wParam == VK_LEFT || wParam == VK_UP) g_config.control.glow_enable = !g_config.control.glow_enable; } //回到原始的游戏窗口地址 return CallWindowProc(g_hooks.original_window_proc, window, msg, wParam, lParam); } //我们自己的present函数 static HRESULT __stdcall my_present(IDirect3DDevice9* device, const RECT* src, const RECT* dest, HWND windowOverride, const RGNDATA* dirtyRegion) noexcept { //初始化imgui的DX9设备 static bool imguiInit{ ImGui_ImplDX9_Init(device) }; device->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_RED | D3DCOLORWRITEENABLE_GREEN | D3DCOLORWRITEENABLE_BLUE); IDirect3DVertexDeclaration9* vertexDeclaration; device->GetVertexDeclaration(&vertexDeclaration); g_imgui.render(); device->SetVertexDeclaration(vertexDeclaration); vertexDeclaration->Release(); return g_hooks.original_present(device, src, dest, windowOverride, dirtyRegion); } //我们自己的reset函数 static HRESULT __stdcall my_reset(IDirect3DDevice9* device, D3DPRESENT_PARAMETERS* params) noexcept { ImGui_ImplDX9_InvalidateDeviceObjects(); auto result = g_hooks.original_reset(device, params); ImGui_ImplDX9_CreateDeviceObjects(); return result; } static int __stdcall do_post_screen_effects(int param) noexcept { if (g_config.engine->is_in_game()) { glow_space::render(); } return g_hooks.clientMode.call_original<int, 44>(param); } static void __stdcall frame_stage_notify(frame_stage_enum stage) noexcept { if (g_config.engine->is_in_game()) { skin_space::run(stage); } g_hooks.client.call_original<void, 37>(stage); } static bool __stdcall create_move(float input_sample_time, user_cmd_struct* cmd) noexcept { //先执行原函数 bool state = g_hooks.clientMode.call_original<bool, 24>(input_sample_time, cmd); //没有命令 if (!cmd->command_number) return state; //更新时间 g_config.global_vars->serverTime(cmd); //在游戏中才操作 if (g_config.engine->is_in_game()) { aim_space::run(cmd); report_space::run(); other_space::again_jump(cmd); } return state; }
8,433
C++
.h
224
33.151786
155
0.735177
FiYHer/csgo_cheats
35
18
4
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,593
model_info.hpp
FiYHer_csgo_cheats/csgo_cheats/model_info.hpp
#pragma once #include "help_func.hpp" class model_info_class { public: //获取模型信息 constexpr auto get_model_index(const char* name) noexcept { return call_virtual_method<int, const char*>(this, 2, name); } };
218
C++
.h
11
17.727273
62
0.746269
FiYHer/csgo_cheats
35
18
4
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,594
glow.hpp
FiYHer_csgo_cheats/csgo_cheats/glow.hpp
#pragma once #include "config.hpp" #include <vector> //辉光对象命名空间 namespace glow_space { //自定义辉光信息 std::vector<std::pair<int, int>> custom_glow_entities; //清空自定义辉光对象 void clear_custom_objects() noexcept { for (const auto& [entity_index, glow_object_index] : custom_glow_entities) g_config.memory.glow_object_mamager->un_register_glow_object(glow_object_index); custom_glow_entities.clear(); } //进行辉光操作 void render() noexcept { if (!g_config.control.glow_enable) return; //获取自身信息 const auto local_player = g_config.entity_list->get_entity(g_config.engine->get_local_player()); if (!local_player) return; //清空所有自定义辉光对象 clear_custom_objects(); //对辉光对象进行操作 for (int i = 0; i < g_config.memory.glow_object_mamager->glow_object_definitions.size; i++) { //获取辉光对象信息 glow_object_definition_struct& glow_object = g_config.memory.glow_object_mamager->glow_object_definitions[i]; //辉光对象 auto set_glow_object = [&](self_vector_struct color, int is_fake) { glow_object.renderWhenOccluded = true;//设置为看不见玩家也辉光 glow_object.alpha = is_fake ? 0.8f : 1.0f;//机器人和真人的透明度不同 glow_object.glowStyle = 0;//默认类型 glow_object.bloomAmount = 1.0f;//机器人和真人的厚度不同 glow_object.glowColor = color;//颜色 }; //获取该辉光对象对应的实例 auto entity = glow_object.entity; if(glow_object.is_unused() || !entity || entity->is_dormant()) continue; //如果不是玩家 if (entity->get_client_class()->classId != classId_enum::CSPlayer) continue; //获取玩家信息 player_info_struct player_info; if (!g_config.engine->get_player_info(entity->get_index(), player_info)) continue; //真实玩家和电脑玩家的辉光颜色有一点差别 if (g_config.control.glow_friend && !entity->is_enemy()) set_glow_object({ 1.0f,0.0f,1.0f }, player_info.fakeplayer); else if (g_config.control.glow_enemy && entity->is_enemy()) { int health = entity->get_health();//获取血量 set_glow_object({ 1.0f - health / 100.0f, health / 100.0f, 0.0f }, player_info.fakeplayer); } } } }
2,130
C++
.h
56
31.892857
120
0.701258
FiYHer/csgo_cheats
35
18
4
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,595
con_var.hpp
FiYHer_csgo_cheats/csgo_cheats/con_var.hpp
#pragma once #include <type_traits> #include "help_func.hpp" #include "utl_vector.hpp" //内存结构数据 typedef struct con_var_struct { //获取浮点型数据 constexpr float get_float() noexcept { return call_virtual_method<float>(this, 12); } //获取整型数据 constexpr int get_int() noexcept { return call_virtual_method<int>(this, 13); } //设置字符串取值 constexpr void set_value(const char* value) noexcept { call_virtual_method<void, const char*>(this, 14, value); } //设置浮点数值 constexpr void set_value(float value) noexcept { call_virtual_method<void, float>(this, 15, value); } //设置整型值 constexpr void set_value(int value) noexcept { call_virtual_method<void, int>(this, 16, value); } std::byte pad[24];//未知数据 std::add_pointer_t<void()> changeCallback;//改变皮肤回调函数 con_var_struct* parent;//父指针 const char* defaultValue;//默认值 char* string;//字符串名称 std::byte pad1[28];//未知数据 utl_vector_class<void()> onChangeCallbacks;//改变皮肤时的回调函数 }con_var_struct;
1,029
C++
.h
40
21.8
58
0.737074
FiYHer/csgo_cheats
35
18
4
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,596
glow_object_definition.hpp
FiYHer_csgo_cheats/csgo_cheats/glow_object_definition.hpp
#pragma once #include "entity.h" #include "self_vector.hpp" #include <cstddef> //辉光对象定义结构 typedef struct glow_object_definition_struct { entity_class* entity; self_vector_struct glowColor; float alpha; std::byte pad[4]; float m_flSomeFloat; float bloomAmount; float m_flAnotherFloat; bool renderWhenOccluded; bool renderWhenUnoccluded; bool fullBloomRender; std::byte pad1; int fullBloomStencilTestValue; int glowStyle; int splitScreenSlot; int nextFreeSlot; constexpr bool is_unused() const noexcept { return nextFreeSlot != ENTRY_IN_USE; } static constexpr int END_OF_FREE_LIST = -1; static constexpr int ENTRY_IN_USE = -2; }glow_object_definition_struct;
703
C++
.h
26
24.961538
83
0.778111
FiYHer/csgo_cheats
35
18
4
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,597
skin.hpp
FiYHer_csgo_cheats/csgo_cheats/skin.hpp
#pragma once #include <algorithm> #include <fstream> #include <vector> #include <limits> #include <map> #include "config.hpp" #include "frame_state.hpp" #include "game_event.hpp" #include "player_info.hpp" #include "weapon_item_definition_index.hpp" #include "weapon_info.hpp" //武器皮肤命名空间 namespace skin_space { //判断图标是否需要变动 static bool hud_update_required = false; //初始化枪械 void initialize_weapon() noexcept { g_config.control.weapon_map.insert({ 42,"Knife" }); g_config.control.weapon_map.insert({ 5028,"Glove" }); g_config.control.weapon_map.insert({ 7, "AK-47" }); g_config.control.weapon_map.insert({ 8, "AUG" }); g_config.control.weapon_map.insert({ 9, "AWP" }); g_config.control.weapon_map.insert({ 63, "CZ75 Auto" }); g_config.control.weapon_map.insert({ 1, "Desert Eagle" }); g_config.control.weapon_map.insert({ 2, "Dual Berettas" }); g_config.control.weapon_map.insert({ 10, "FAMAS" }); g_config.control.weapon_map.insert({ 3, "Five-SeveN" }); g_config.control.weapon_map.insert({ 11, "G3SG1" }); g_config.control.weapon_map.insert({ 13, "Galil AR" }); g_config.control.weapon_map.insert({ 4, "Glock-18" }); g_config.control.weapon_map.insert({ 14, "M249" }); g_config.control.weapon_map.insert({ 60, "M4A1-S" }); g_config.control.weapon_map.insert({ 16, "M4A4" }); g_config.control.weapon_map.insert({ 17, "MAC-10" }); g_config.control.weapon_map.insert({ 27, "MAG-7" }); g_config.control.weapon_map.insert({ 23, "MP5-SD" }); g_config.control.weapon_map.insert({ 33, "MP7" }); g_config.control.weapon_map.insert({ 34, "MP9" }); g_config.control.weapon_map.insert({ 28, "Negev" }); g_config.control.weapon_map.insert({ 35, "Nova" }); g_config.control.weapon_map.insert({ 32, "P2000" }); g_config.control.weapon_map.insert({ 36, "P250" }); g_config.control.weapon_map.insert({ 19, "P90" }); g_config.control.weapon_map.insert({ 26, "PP-Bizon" }); g_config.control.weapon_map.insert({ 64, "R8 Revolver" }); g_config.control.weapon_map.insert({ 29, "Sawed-Off" }); g_config.control.weapon_map.insert({ 38, "SCAR-20" }); g_config.control.weapon_map.insert({ 40, "SSG 08" }); g_config.control.weapon_map.insert({ 39, "SG 553" }); g_config.control.weapon_map.insert({ 30, "Tec-9" }); g_config.control.weapon_map.insert({ 24, "UMP-45" }); g_config.control.weapon_map.insert({ 61, "USP-S" }); g_config.control.weapon_map.insert({ 25, "XM1014" }); } //初始化相关 void initialize_skin() noexcept { //读取游戏武器皮肤文件 std::ifstream items{ "csgo/scripts/items/items_game_cdn.txt" }; //将文件数据存放到string const std::string gameItems{ std::istreambuf_iterator<char>{ items }, std::istreambuf_iterator<char>{ } }; //关闭文件 items.close(); //开始遍历 for (int i = 0; i < g_config.memory.weapen_item_schema()->paintKits.lastElement; i++) { //获取武器信息 const auto paint_kit = g_config.memory.weapen_item_schema()->paintKits.memory[i].value; if (paint_kit->id == 9001) continue; //获取名称 const auto item_name{ g_config.localize->find(paint_kit->itemName.buffer + 1) }; //获取长度 const int item_name_length = WideCharToMultiByte(CP_UTF8, 0, item_name, -1, nullptr, 0, nullptr, nullptr); //转化为string if (std::string name(item_name_length, 0); WideCharToMultiByte(CP_UTF8, 0, item_name, -1, &name[0], item_name_length, nullptr, nullptr)) { if (paint_kit->id < 10000)//武器皮肤 { std::string weapen_name; if (auto pos = gameItems.find('_' + std::string{ paint_kit->name.buffer } +'='); pos != std::string::npos && gameItems.substr(pos + paint_kit->name.length).find('_' + std::string{ paint_kit->name.buffer } +'=') == std::string::npos) { if (auto weaponName = gameItems.rfind("weapon_", pos); weaponName != std::string::npos) { name.back() = ' '; weapen_name = gameItems.substr(weaponName + 7, pos - weaponName - 7); weapen_name += "-" + name; } } if (weapen_name.size() && weapen_name[0] >= 'a' && weapen_name[0] <= 'z') g_config.control.skin_vector.emplace_back(paint_kit->id, std::move(weapen_name)); else g_config.control.skin_vector.emplace_back(paint_kit->id, "null"); } } } //排序分类 std::sort(g_config.control.skin_vector.begin(), g_config.control.skin_vector.end()); } //初始化小刀 void initialize_knife() noexcept { g_config.control.knife_vector.push_back({ 0, "Default" }); g_config.control.knife_vector.push_back({ WEAPON_KNIFE_BAYONET, "Bayonet" }); g_config.control.knife_vector.push_back({ WEAPON_KNIFE_CSS, "Classic Knife" }); g_config.control.knife_vector.push_back({ WEAPON_KNIFE_SKELETON, "Skeleton Knife" }); g_config.control.knife_vector.push_back({ WEAPON_KNIFE_OUTDOOR, "Nomad Knife" }); g_config.control.knife_vector.push_back({ WEAPON_KNIFE_CORD, "Paracord Knife" }); g_config.control.knife_vector.push_back({ WEAPON_KNIFE_CANIS, "Survival Knife" }); g_config.control.knife_vector.push_back({ WEAPON_KNIFE_FLIP, "Flip Knife" }); g_config.control.knife_vector.push_back({ WEAPON_KNIFE_GUT, "Gut Knife" }); g_config.control.knife_vector.push_back({ WEAPON_KNIFE_KARAMBIT, "Karambit" }); g_config.control.knife_vector.push_back({ WEAPON_KNIFE_M9_BAYONET, "M9 Bayonet" }); g_config.control.knife_vector.push_back({ WEAPON_KNIFE_TACTICAL, "Huntsman Knife" }); g_config.control.knife_vector.push_back({ WEAPON_KNIFE_FALCHION, "Falchion Knife" }); g_config.control.knife_vector.push_back({ WEAPON_KNIFE_SURVIVAL_BOWIE, "Bowie Knife" }); g_config.control.knife_vector.push_back({ WEAPON_KNIFE_BUTTERFLY, "Butterfly Knife" }); g_config.control.knife_vector.push_back({ WEAPON_KNIFE_PUSH, "Shadow Daggers" }); g_config.control.knife_vector.push_back({ WEAPON_KNIFE_URSUS, "Ursus Knife" }); g_config.control.knife_vector.push_back({ WEAPON_KNIFE_GYPSY_JACKKNIFE, "Navaja Knife" }); g_config.control.knife_vector.push_back({ WEAPON_KNIFE_STILETTO, "Stiletto Knife" }); g_config.control.knife_vector.push_back({ WEAPON_KNIFE_WIDOWMAKER, "Talon Knife" }); } //获取手套和小刀信息 const weapon_info_struct* get_knife_glove_info(int index = -1) noexcept { //手套和小刀的信息 const static std::map<int, weapon_info_struct> info = { {WEAPON_KNIFE,{"models/weapons/v_knife_default_ct.mdl", "knife"}}, {WEAPON_KNIFE_T,{"models/weapons/v_knife_default_t.mdl", "knife_t"}}, {WEAPON_KNIFE_BAYONET,{"models/weapons/v_knife_bayonet.mdl", "bayonet"}}, {WEAPON_KNIFE_CSS,{"models/weapons/v_knife_css.mdl", "knife_css"}}, {WEAPON_KNIFE_SKELETON,{"models/weapons/v_knife_skeleton.mdl", "knife_skeleton"}}, {WEAPON_KNIFE_OUTDOOR,{"models/weapons/v_knife_outdoor.mdl", "knife_outdoor"}}, {WEAPON_KNIFE_CORD,{"models/weapons/v_knife_cord.mdl", "knife_cord"}}, {WEAPON_KNIFE_CANIS,{"models/weapons/v_knife_canis.mdl", "knife_canis"}}, {WEAPON_KNIFE_FLIP,{"models/weapons/v_knife_flip.mdl", "knife_flip"}}, {WEAPON_KNIFE_GUT,{"models/weapons/v_knife_gut.mdl", "knife_gut"}}, {WEAPON_KNIFE_KARAMBIT, {"models/weapons/v_knife_karam.mdl", "knife_karambit"}}, {WEAPON_KNIFE_M9_BAYONET, {"models/weapons/v_knife_m9_bay.mdl", "knife_m9_bayonet"}}, {WEAPON_KNIFE_TACTICAL, {"models/weapons/v_knife_tactical.mdl", "knife_tactical"}}, {WEAPON_KNIFE_FALCHION, {"models/weapons/v_knife_falchion_advanced.mdl", "knife_falchion"}}, {WEAPON_KNIFE_SURVIVAL_BOWIE, {"models/weapons/v_knife_survival_bowie.mdl", "knife_survival_bowie"}}, {WEAPON_KNIFE_BUTTERFLY, {"models/weapons/v_knife_butterfly.mdl", "knife_butterfly"}}, {WEAPON_KNIFE_PUSH, {"models/weapons/v_knife_push.mdl", "knife_push"}}, {WEAPON_KNIFE_URSUS,{"models/weapons/v_knife_ursus.mdl", "knife_ursus"}}, {WEAPON_KNIFE_GYPSY_JACKKNIFE,{"models/weapons/v_knife_gypsy_jackknife.mdl", "knife_gypsy_jackknife"}}, {WEAPON_KNIFE_STILETTO,{"models/weapons/v_knife_stiletto.mdl", "knife_stiletto"}}, {WEAPON_KNIFE_WIDOWMAKER,{"models/weapons/v_knife_widowmaker.mdl", "knife_widowmaker"}}, {GLOVE_STUDDED_BLOODHOUND,{"models/weapons/w_models/arms/w_glove_bloodhound.mdl"}}, {GLOVE_T_SIDE,{"models/weapons/w_models/arms/w_glove_fingerless.mdl"}}, {GLOVE_CT_SIDE,{"models/weapons/w_models/arms/w_glove_hardknuckle.mdl"}}, {GLOVE_SPORTY,{"models/weapons/w_models/arms/w_glove_sporty.mdl"}}, {GLOVE_SLICK,{"models/weapons/w_models/arms/w_glove_slick.mdl"}}, {GLOVE_LEATHER_WRAP,{"models/weapons/w_models/arms/w_glove_handwrap_leathery.mdl"}}, {GLOVE_MOTORCYCLE,{"models/weapons/w_models/arms/w_glove_motorcycle.mdl"}}, {GLOVE_SPECIALIST,{"models/weapons/w_models/arms/w_glove_specialist.mdl"}}, {GLOVE_HYDRA,{"models/weapons/w_models/arms/w_glove_bloodhound_hydra.mdl"}} }; const auto entry = info.find(index); return entry == end(info) ? nullptr : &entry->second; } //判断是否是小刀 bool is_knife(const int i) noexcept { return (i >= WEAPON_KNIFE_BAYONET && i < GLOVE_STUDDED_BLOODHOUND) || i == WEAPON_KNIFE_T || i == WEAPON_KNIFE; } //更新武器皮肤数据 void update_weapen_data(entity_class* entity) noexcept { //获取索引 const auto local_index = entity->get_index(); //玩家死亡 if (!entity->is_alive()) return; //获取玩家信息 player_info_struct player_info; if (!g_config.engine->get_player_info(local_index, player_info)) return; //获取武器信息 auto& weapons_info = entity->get_weapons(); //遍历武器信息 for (auto weapon_handle : weapons_info) { //没有武器 if(weapon_handle == -1) break; //获取武器 auto weapon = g_config.entity_list->get_entity_from_handle(weapon_handle); if (!weapon) continue; //强制使用 weapon->get_item_id_high() = -1; //设置用户ID weapon->get_account_id() = player_info.xuidLow; //设置武器皮肤ID weapon->get_fallback_paint_kit() = g_config.control.weapon_skin_id; //获取小刀信息 if (is_knife(weapon->get_item_definition_index())) { if (const auto knife_glove_info = get_knife_glove_info(g_config.control.knife_index)) { weapon->get_item_definition_index() = g_config.control.knife_index; weapon->set_model_index(g_config.model_info->get_model_index(knife_glove_info->model)); weapon->pre_data_update(0); } } } //获取视图模型 const auto view_model = g_config.entity_list->get_entity_from_handle(entity->get_view_model()); if (!view_model) return; //获取视图中的武器 const auto view_model_weapon = g_config.entity_list->get_entity_from_handle(view_model->get_weapon()); if (!view_model_weapon) return; //获取小刀信息 const auto override_info = get_knife_glove_info(view_model_weapon->get_item_definition_index()); if (!override_info) return; //获取覆盖视图索引 const auto override_model_index = g_config.model_info->get_model_index(override_info->model); view_model->get_model_index() = override_model_index; //获取世界模型 const auto world_model = g_config.entity_list->get_entity_from_handle(view_model_weapon->get_weapon_world_model()); if (!world_model) return; //设置世界模型 world_model->get_model_index() = override_model_index + 1; } //更新图标 void update_hud() noexcept { if (auto hud_weapons = g_config.memory.find_hud_element(g_config.memory.hud, "CCSGO_HudWeaponSelection") - 0x28) { for (int i = 0; i < *(hud_weapons + 0x20); i++) i = g_config.memory.clear_hud_weapon(hud_weapons, i); } //图标更新完成 hud_update_required = false; } //切换武器皮肤 void run(frame_stage_enum state) noexcept { //没开 if (!g_config.control.skin_enable) return; //更新武器皮肤帧 if (state == frame_stage_enum::NET_UPDATE_POSTDATAUPDATE_START) { //获取自己信息 if (const auto local_player = g_config.entity_list->get_entity(g_config.engine->get_local_player())) { //更新武器皮肤数据 update_weapen_data(local_player); //更新图标 if (hud_update_required && !local_player->is_dormant()) update_hud(); } } } //安排hud更新 void schedule_hud_update() noexcept { //调用骨骼皮肤回调函数 g_config.cvar->findVar("cl_fullupdate")->changeCallback(); //需要更新图标 hud_update_required = true; } }
12,117
C++
.h
266
41.048872
132
0.692381
FiYHer/csgo_cheats
35
18
4
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,598
client.hpp
FiYHer_csgo_cheats/csgo_cheats/client.hpp
#pragma once #include "help_func.hpp" #include "client_class.hpp" //客户类 class client_class { public: //获取所有的类 constexpr auto get_all_classes() noexcept { return call_virtual_method<client_class_struct*>(this, 8); } };
233
C++
.h
13
15.769231
60
0.753555
FiYHer/csgo_cheats
35
18
4
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,599
game_ui.hpp
FiYHer_csgo_cheats/csgo_cheats/game_ui.hpp
#pragma once #include "help_func.hpp" //游戏ui消息显示类 class game_ui_class { public: //显示游戏窗口消息 constexpr void message_box(const char* title, const char* text) noexcept { call_virtual_method<void, const char*, const char*, bool, bool, const char*, const char*, const char*, const char*, void*>(this, 20, title, text, true, false, nullptr, nullptr, nullptr, nullptr, nullptr); } };
397
C++
.h
12
30.333333
206
0.732432
FiYHer/csgo_cheats
35
18
4
GPL-3.0
9/20/2024, 10:44:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false