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,541,683
ITrackingDevice.h
KinectToVR_k2vr-application/external/Kinect/ITrackingDevice.h
#pragma once #include <string> #include <vector> #include <windows.h> class ITrackingDevice { // Interface base for K2 Tracking Device public: virtual ~ITrackingDevice() {} virtual void initialize() = 0; virtual HRESULT getStatusResult() = 0; virtual std::string statusResultString(HRESULT stat) = 0; virtual void update() = 0; bool isInitialized() { return initialized; } bool isZeroed() { return zeroed; } bool zeroed = false; protected: bool initialized= false; class FailedKinectInitialisation : public std::exception { virtual const char* what() const throw() { return "Failure to initialize the Kinect sensor. Is it plugged in and supplied with power?"; } } FailedKinectInitialisation; private: };
801
C++
.h
26
26.076923
104
0.697128
KinectToVR/k2vr-application
38
4
0
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,686
EthernetUdp.h
khoih-prog_MDNS_Generic/LibraryPatches/Portenta/Ethernet/EthernetUdp.h
/* EthernetUdp.h Copyright (c) 2021 Arduino SA. 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 ethernetudp_h #define ethernetudp_h #include "Ethernet.h" #if 0 #include "MbedUdp.h" namespace arduino { class EthernetUDP : public MbedUDP { NetworkInterface *getNetwork() { return Ethernet.getNetwork(); } }; } #endif #include "api/Udp.h" #include "netsocket/SocketAddress.h" #include "netsocket/UDPSocket.h" #define UDP_TX_PACKET_MAX_SIZE 24 #include "api/Udp.h" #include "netsocket/SocketAddress.h" #include "netsocket/UDPSocket.h" #define UDP_TX_PACKET_MAX_SIZE 24 namespace arduino { class EthernetUDP : public UDP { private: UDPSocket _socket; // Mbed OS socket SocketAddress _host; // Host to be used to send data SocketAddress _remoteHost; // Remote host that sent incoming packets uint8_t* _packet_buffer; // Raw packet buffer (contains data we got from the UDPSocket) // The Arduino APIs allow you to iterate through this buffer, so we need to be able to iterate over the current packet // these two variables are used to cache the state of the current packet uint8_t* _current_packet; size_t _current_packet_size; public: EthernetUDP(); // Constructor ~EthernetUDP(); virtual uint8_t begin(uint16_t); // initialize, start listening on specified port. Returns 1 if successful, 0 if there are no sockets available to use virtual uint8_t beginMulticast(IPAddress, uint16_t); // initialize, start listening on specified multicast IP address and port. Returns 1 if successful, 0 if there are no sockets available to use virtual void stop(); // Finish with the UDP socket // Sending UDP packets // Start building up a packet to send to the remote host specific in ip and port // Returns 1 if successful, 0 if there was a problem with the supplied IP address or port virtual int beginPacket(IPAddress ip, uint16_t port); // Start building up a packet to send to the remote host specific in host and port // Returns 1 if successful, 0 if there was a problem resolving the hostname or port virtual int beginPacket(const char *host, uint16_t port); // Finish off this packet and send it // Returns 1 if the packet was sent successfully, 0 if there was an error virtual int endPacket(); // Write a single byte into the packet virtual size_t write(uint8_t); // Write size bytes from buffer into the packet virtual size_t write(const uint8_t *buffer, size_t size); using Print::write; // Start processing the next available incoming packet // Returns the size of the packet in bytes, or 0 if no packets are available virtual int parsePacket(); // Number of bytes remaining in the current packet virtual int available(); // Read a single byte from the current packet virtual int read(); // Read up to len bytes from the current packet and place them into buffer // Returns the number of bytes read, or 0 if none are available virtual int read(unsigned char* buffer, size_t len); // Read up to len characters from the current packet and place them into buffer // Returns the number of characters read, or 0 if none are available virtual int read(char* buffer, size_t len) { return read((unsigned char*)buffer, len); }; // Return the next byte from the current packet without moving on to the next byte virtual int peek(); virtual void flush(); // Finish reading the current packet // Return the IP address of the host who sent the current incoming packet virtual IPAddress remoteIP(); // // Return the port of the host who sent the current incoming packet virtual uint16_t remotePort(); }; } #endif
4,340
C++
.h
91
44.923077
198
0.760427
khoih-prog/MDNS_Generic
37
12
0
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,688
defines.h
khoih-prog_MDNS_Generic/examples/Ethernet/RegisteringServices/defines.h
/**************************************************************************************************************************** defines.h mDNS library to support mDNS (registering services) and DNS-SD (service discovery). Based on and modified from https://github.com/arduino-libraries/ArduinoMDNS Built by Khoi Hoang https://github.com/khoih-prog/MDNS_Generic Licensed under MIT license Original Author: Georg Kaindl (http://gkaindl.com) This file is part of Arduino EthernetBonjour. EthernetBonjour 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 3 of the License, or (at your option) any later version. EthernetBonjour 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 EthernetBonjour. If not, see <http://www.gnu.org/licenses/>. ***************************************************************************************************************************************/ #ifndef defines_h #define defines_h #define MDNS_DEBUG_PORT Serial // Debug Level from 0 to 4 #define _MDNS_LOGLEVEL_ 2 #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(__SAMD21G18A__) \ || defined(ARDUINO_SAMD_CIRCUITPLAYGROUND_EXPRESS) || defined(__SAMD21E18A__) || defined(__SAMD51__) || defined(__SAMD51J20A__) || defined(__SAMD51J19A__) \ || defined(__SAMD51G19A__) || defined(__SAMD51P19A__) || defined(__SAMD21G18A__) ) #if defined(ETHERNET_USE_SAMD) #undef ETHERNET_USE_SAMD #endif #define ETHERNET_USE_SAMD true #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(ETHERNET_USE_NRF528XX) #undef ETHERNET_USE_NRF528XX #endif #define ETHERNET_USE_NRF528XX true #endif #if ( defined(ARDUINO_SAM_DUE) || defined(__SAM3X8E__) ) #if defined(ETHERNET_USE_SAM_DUE) #undef ETHERNET_USE_SAM_DUE #endif #define ETHERNET_USE_SAM_DUE true #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(ETHERNET_USE_STM32) #undef ETHERNET_USE_STM32 #endif #define ETHERNET_USE_STM32 true #endif #if ( defined(ARDUINO_ARCH_RP2040) || defined(ARDUINO_RASPBERRY_PI_PICO) || defined(ARDUINO_ADAFRUIT_FEATHER_RP2040) || defined(ARDUINO_GENERIC_RP2040) ) #if defined(ETHERNET_USE_RP2040) #undef ETHERNET_USE_RP2040 #endif #define ETHERNET_USE_RP2040 true #if defined(ETHERNET_USE_RPIPICO) #undef ETHERNET_USE_RPIPICO #endif #define ETHERNET_USE_RPIPICO true #endif #if ( defined(ARDUINO_PORTENTA_H7_M7) || defined(ARDUINO_PORTENTA_H7_M4) ) #if defined(BOARD_NAME) #undef BOARD_NAME #endif #if defined(CORE_CM7) #warning Using Portenta H7 M7 core #define BOARD_NAME "PORTENTA_H7_M7" #else #warning Using Portenta H7 M4 core #define BOARD_NAME "PORTENTA_H7_M4" #endif #elif defined(ETHERNET_USE_SAMD) // For SAMD // Default pin 10 to SS/CS #define USE_THIS_SS_PIN 10 #if ( defined(ARDUINO_SAMD_ZERO) && !defined(SEEED_XIAO_M0) ) #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" #define USE_THIS_SS_PIN 10 #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" #ifdef USE_THIS_SS_PIN #undef USE_THIS_SS_PIN #endif #define USE_THIS_SS_PIN A1 #warning define SEEED_XIAO_M0 USE_THIS_SS_PIN == A1 #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(__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 #elif (ETHERNET_USE_SAM_DUE) // Default pin 10 to SS/CS #define USE_THIS_SS_PIN 10 #define BOARD_TYPE "SAM DUE" #elif (ETHERNET_USE_NRF528XX) // Default pin 10 to SS/CS #define USE_THIS_SS_PIN 10 #if defined(NRF52840_FEATHER) #define BOARD_TYPE "NRF52840_FEATHER" #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" #define USE_THIS_SS_PIN 10 // For other boards #elif defined(NRF52840_CIRCUITPLAY) #define BOARD_TYPE "NRF52840_CIRCUITPLAY" #elif defined(NRF52840_CLUE) #define BOARD_TYPE "NRF52840_CLUE" #elif defined(NRF52840_METRO) #define BOARD_TYPE "NRF52840_METRO" #elif defined(NRF52840_PCA10056) #define BOARD_TYPE "NRF52840_PCA10056" #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(ARDUINO_NRF52_ADAFRUIT) #define BOARD_TYPE "ARDUINO_NRF52_ADAFRUIT" #else #define BOARD_TYPE "nRF52 Unknown" #endif #elif ( defined(CORE_TEENSY) ) // Default pin 10 to SS/CS #define USE_THIS_SS_PIN 10 #if defined(__IMXRT1062__) // For Teensy 4.1/4.0 #if defined(ARDUINO_TEENSY41) #define BOARD_TYPE "TEENSY 4.1" // Use true for NativeEthernet Library, false if using other Ethernet libraries #define USE_NATIVE_ETHERNET true #elif defined(ARDUINO_TEENSY40) #define BOARD_TYPE "TEENSY 4.0" #else #define BOARD_TYPE "TEENSY 4.x" #endif #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 #elif (ETHERNET_USE_STM32) #if defined(STM32F0) #define BOARD_TYPE "STM32F0" #elif defined(STM32F1) #define BOARD_TYPE "STM32F1" #elif defined(STM32F2) #define BOARD_TYPE "STM32F2" #elif defined(STM32F3) #define BOARD_TYPE "STM32F3" #elif defined(STM32F4) #define BOARD_TYPE "STM32F4" #elif defined(STM32F7) #define BOARD_TYPE "STM32F7" #elif defined(STM32L0) #define BOARD_TYPE "STM32L0" #elif defined(STM32L1) #define BOARD_TYPE "STM32L1" #elif defined(STM32L4) #define BOARD_TYPE "STM32L4" #elif defined(STM32H7) #define BOARD_TYPE "STM32H7" #elif defined(STM32G0) #define BOARD_TYPE "STM32G0" #elif defined(STM32G4) #define BOARD_TYPE "STM32G4" #elif defined(STM32WB) #define BOARD_TYPE "STM32WB" #elif defined(STM32MP1) #define BOARD_TYPE "STM32MP1" #else #define BOARD_TYPE "STM32 Unknown" #endif #elif (ETHERNET_USE_RP2040 || ETHERNET_USE_RPIPICO) // Default pin 5 (in Mbed) or 17 to SS/CS #if defined(ARDUINO_ARCH_MBED) // For RPI Pico using Arduino Mbed RP2040 core // SCK: GPIO2, MOSI: GPIO3, MISO: GPIO4, SS/CS: GPIO5 #define USE_THIS_SS_PIN 17 #if defined(BOARD_NAME) #undef BOARD_NAME #endif #if defined(ARDUINO_RASPBERRY_PI_PICO) #define BOARD_TYPE "MBED RASPBERRY_PI_PICO" #elif defined(ARDUINO_ADAFRUIT_FEATHER_RP2040) #define BOARD_TYPE "MBED DAFRUIT_FEATHER_RP2040" #elif defined(ARDUINO_GENERIC_RP2040) #define BOARD_TYPE "MBED GENERIC_RP2040" #else #define BOARD_TYPE "MBED Unknown RP2040" #endif #else //#define USING_SPI2 true // For RPI Pico using E. Philhower RP2040 core #if (USING_SPI2) // SCK: GPIO14, MOSI: GPIO15, MISO: GPIO12, SS/CS: GPIO13 for SPI1 #define USE_THIS_SS_PIN 13 #else // SCK: GPIO18, MOSI: GPIO19, MISO: GPIO16, SS/CS: GPIO17 for SPI0 #define USE_THIS_SS_PIN 17 #endif #endif #define SS_PIN_DEFAULT USE_THIS_SS_PIN // For RPI Pico #warning Use RPI-Pico RP2040 architecture #else // For Mega // Default pin 10 to SS/CS #define USE_THIS_SS_PIN 10 // Reduce size for Mega #define SENDCONTENT_P_BUFFER_SZ 512 #define BOARD_TYPE "AVR Mega" #endif #if defined(ARDUINO_BOARD) #define BOARD_NAME ARDUINO_BOARD #elif !defined(BOARD_NAME) #define BOARD_NAME BOARD_TYPE #endif #include <SPI.h> // UIPEthernet, Ethernet_Shield_W5200, EtherCard, EtherSia libraries are not supported // To override the default CS/SS pin. Don't use unless you know exactly which pin to use // You can define here or customize for each board at same place with BOARD_TYPE // Check @ defined(SEEED_XIAO_M0) //#define USE_THIS_SS_PIN 22 //21 //5 //4 //2 //15 // Only one if the following to be true #define USE_ETHERNET_GENERIC true #define USE_ETHERNET_PORTENTA_H7 false #if USE_ETHERNET_PORTENTA_H7 //#include "PortentaEthernet.h" #include "Ethernet.h" #include "EthernetUdp.h" #warning Using Portenta_Ethernet lib for Portenta_H7. #define SHIELD_TYPE "Ethernet using Portenta_Ethernet Library" #elif USE_ETHERNET_GENERIC #include "Ethernet_Generic.h" #include "EthernetUdp.h" #warning Use Ethernet_Generic lib #define SHIELD_TYPE "W5x00 using Ethernet_Generic Library" #elif USE_ETHERNET #include "Ethernet.h" #include "EthernetUdp.h" #warning Use Ethernet lib #define SHIELD_TYPE "W5x00 using Ethernet Library" #elif USE_ETHERNET_LARGE #include "EthernetLarge.h" #include "EthernetUdp.h" #warning Use EthernetLarge lib #define SHIELD_TYPE "W5x00 using EthernetLarge Library" #elif USE_ETHERNET2 #include "Ethernet2.h" #include "EthernetUdp2.h" #warning Use Ethernet2 lib #define SHIELD_TYPE "W5x00 using Ethernet2 Library" #elif USE_ETHERNET3 #include "Ethernet3.h" #include "EthernetUdp3.h" #warning Use Ethernet3 lib #define SHIELD_TYPE "W5x00 using Ethernet3 Library" #else #define USE_ETHERNET_GENERIC true #include "Ethernet_Generic.h" #include "EthernetUdp.h" #warning Use Ethernet_Generic lib #define SHIELD_TYPE "W5x00 using default Ethernet_Generic Library" #endif // Enter a MAC address and IP address for your controller below. #define NUMBER_OF_MAC 20 byte mac[][NUMBER_OF_MAC] = { { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x01 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x02 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x03 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x04 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x05 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x06 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x07 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x08 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x09 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0A }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0B }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0C }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0D }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0E }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0F }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x10 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x11 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x12 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x13 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x14 }, }; // Select the IP address according to your local network IPAddress ip(192, 168, 2, 222); #endif //defines_h
16,853
C++
.h
399
38.358396
162
0.685342
khoih-prog/MDNS_Generic
37
12
0
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,689
defines.h
khoih-prog_MDNS_Generic/examples/Ethernet/ResolvingHostNames/defines.h
/**************************************************************************************************************************** defines.h mDNS library to support mDNS (registering services) and DNS-SD (service discovery). Based on and modified from https://github.com/arduino-libraries/ArduinoMDNS Built by Khoi Hoang https://github.com/khoih-prog/MDNS_Generic Licensed under MIT license Original Author: Georg Kaindl (http://gkaindl.com) This file is part of Arduino EthernetBonjour. EthernetBonjour 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 3 of the License, or (at your option) any later version. EthernetBonjour 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 EthernetBonjour. If not, see <http://www.gnu.org/licenses/>. ***************************************************************************************************************************************/ #ifndef defines_h #define defines_h #define MDNS_DEBUG_PORT Serial // Debug Level from 0 to 4 #define _MDNS_LOGLEVEL_ 1 #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(__SAMD21G18A__) \ || defined(ARDUINO_SAMD_CIRCUITPLAYGROUND_EXPRESS) || defined(__SAMD21E18A__) || defined(__SAMD51__) || defined(__SAMD51J20A__) || defined(__SAMD51J19A__) \ || defined(__SAMD51G19A__) || defined(__SAMD51P19A__) || defined(__SAMD21G18A__) ) #if defined(ETHERNET_USE_SAMD) #undef ETHERNET_USE_SAMD #endif #define ETHERNET_USE_SAMD true #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(ETHERNET_USE_NRF528XX) #undef ETHERNET_USE_NRF528XX #endif #define ETHERNET_USE_NRF528XX true #endif #if ( defined(ARDUINO_SAM_DUE) || defined(__SAM3X8E__) ) #if defined(ETHERNET_USE_SAM_DUE) #undef ETHERNET_USE_SAM_DUE #endif #define ETHERNET_USE_SAM_DUE true #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(ETHERNET_USE_STM32) #undef ETHERNET_USE_STM32 #endif #define ETHERNET_USE_STM32 true #endif #if ( defined(ARDUINO_ARCH_RP2040) || defined(ARDUINO_RASPBERRY_PI_PICO) || defined(ARDUINO_ADAFRUIT_FEATHER_RP2040) || defined(ARDUINO_GENERIC_RP2040) ) #if defined(ETHERNET_USE_RP2040) #undef ETHERNET_USE_RP2040 #endif #define ETHERNET_USE_RP2040 true #if defined(ETHERNET_USE_RPIPICO) #undef ETHERNET_USE_RPIPICO #endif #define ETHERNET_USE_RPIPICO true #endif #if ( defined(ARDUINO_PORTENTA_H7_M7) || defined(ARDUINO_PORTENTA_H7_M4) ) #if defined(BOARD_NAME) #undef BOARD_NAME #endif #if defined(CORE_CM7) #warning Using Portenta H7 M7 core #define BOARD_NAME "PORTENTA_H7_M7" #else #warning Using Portenta H7 M4 core #define BOARD_NAME "PORTENTA_H7_M4" #endif #elif defined(ETHERNET_USE_SAMD) // For SAMD // Default pin 10 to SS/CS #define USE_THIS_SS_PIN 10 #if ( defined(ARDUINO_SAMD_ZERO) && !defined(SEEED_XIAO_M0) ) #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" #define USE_THIS_SS_PIN 10 #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" #ifdef USE_THIS_SS_PIN #undef USE_THIS_SS_PIN #endif #define USE_THIS_SS_PIN A1 #warning define SEEED_XIAO_M0 USE_THIS_SS_PIN == A1 #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(__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 #elif (ETHERNET_USE_SAM_DUE) // Default pin 10 to SS/CS #define USE_THIS_SS_PIN 10 #define BOARD_TYPE "SAM DUE" #elif (ETHERNET_USE_NRF528XX) // Default pin 10 to SS/CS #define USE_THIS_SS_PIN 10 #if defined(NRF52840_FEATHER) #define BOARD_TYPE "NRF52840_FEATHER" #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" #define USE_THIS_SS_PIN 10 // For other boards #elif defined(NRF52840_CIRCUITPLAY) #define BOARD_TYPE "NRF52840_CIRCUITPLAY" #elif defined(NRF52840_CLUE) #define BOARD_TYPE "NRF52840_CLUE" #elif defined(NRF52840_METRO) #define BOARD_TYPE "NRF52840_METRO" #elif defined(NRF52840_PCA10056) #define BOARD_TYPE "NRF52840_PCA10056" #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(ARDUINO_NRF52_ADAFRUIT) #define BOARD_TYPE "ARDUINO_NRF52_ADAFRUIT" #else #define BOARD_TYPE "nRF52 Unknown" #endif #elif ( defined(CORE_TEENSY) ) // Default pin 10 to SS/CS #define USE_THIS_SS_PIN 10 #if defined(__IMXRT1062__) // For Teensy 4.1/4.0 #if defined(ARDUINO_TEENSY41) #define BOARD_TYPE "TEENSY 4.1" // Use true for NativeEthernet Library, false if using other Ethernet libraries #define USE_NATIVE_ETHERNET true #elif defined(ARDUINO_TEENSY40) #define BOARD_TYPE "TEENSY 4.0" #else #define BOARD_TYPE "TEENSY 4.x" #endif #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 #elif (ETHERNET_USE_STM32) #if defined(STM32F0) #define BOARD_TYPE "STM32F0" #elif defined(STM32F1) #define BOARD_TYPE "STM32F1" #elif defined(STM32F2) #define BOARD_TYPE "STM32F2" #elif defined(STM32F3) #define BOARD_TYPE "STM32F3" #elif defined(STM32F4) #define BOARD_TYPE "STM32F4" #elif defined(STM32F7) #define BOARD_TYPE "STM32F7" #elif defined(STM32L0) #define BOARD_TYPE "STM32L0" #elif defined(STM32L1) #define BOARD_TYPE "STM32L1" #elif defined(STM32L4) #define BOARD_TYPE "STM32L4" #elif defined(STM32H7) #define BOARD_TYPE "STM32H7" #elif defined(STM32G0) #define BOARD_TYPE "STM32G0" #elif defined(STM32G4) #define BOARD_TYPE "STM32G4" #elif defined(STM32WB) #define BOARD_TYPE "STM32WB" #elif defined(STM32MP1) #define BOARD_TYPE "STM32MP1" #else #define BOARD_TYPE "STM32 Unknown" #endif #elif (ETHERNET_USE_RP2040 || ETHERNET_USE_RPIPICO) // Default pin 5 (in Mbed) or 17 to SS/CS #if defined(ARDUINO_ARCH_MBED) // For RPI Pico using Arduino Mbed RP2040 core // SCK: GPIO2, MOSI: GPIO3, MISO: GPIO4, SS/CS: GPIO5 #define USE_THIS_SS_PIN 17 #if defined(BOARD_NAME) #undef BOARD_NAME #endif #if defined(ARDUINO_RASPBERRY_PI_PICO) #define BOARD_TYPE "MBED RASPBERRY_PI_PICO" #elif defined(ARDUINO_ADAFRUIT_FEATHER_RP2040) #define BOARD_TYPE "MBED DAFRUIT_FEATHER_RP2040" #elif defined(ARDUINO_GENERIC_RP2040) #define BOARD_TYPE "MBED GENERIC_RP2040" #else #define BOARD_TYPE "MBED Unknown RP2040" #endif #else #define USING_SPI2 true // For RPI Pico using E. Philhower RP2040 core #if (USING_SPI2) // SCK: GPIO14, MOSI: GPIO15, MISO: GPIO12, SS/CS: GPIO13 for SPI1 #define USE_THIS_SS_PIN 13 #else // SCK: GPIO18, MOSI: GPIO19, MISO: GPIO16, SS/CS: GPIO17 for SPI0 #define USE_THIS_SS_PIN 17 #endif #endif #define SS_PIN_DEFAULT USE_THIS_SS_PIN // For RPI Pico #warning Use RPI-Pico RP2040 architecture #else // For Mega // Default pin 10 to SS/CS #define USE_THIS_SS_PIN 10 // Reduce size for Mega #define SENDCONTENT_P_BUFFER_SZ 512 #define BOARD_TYPE "AVR Mega" #endif #if defined(ARDUINO_BOARD) #define BOARD_NAME ARDUINO_BOARD #elif !defined(BOARD_NAME) #define BOARD_NAME BOARD_TYPE #endif #include <SPI.h> // UIPEthernet, Ethernet_Shield_W5200, EtherCard, EtherSia libraries are not supported // To override the default CS/SS pin. Don't use unless you know exactly which pin to use // You can define here or customize for each board at same place with BOARD_TYPE // Check @ defined(SEEED_XIAO_M0) //#define USE_THIS_SS_PIN 22 //21 //5 //4 //2 //15 // Only one if the following to be true #define USE_ETHERNET_GENERIC true #define USE_ETHERNET_PORTENTA_H7 false #if USE_ETHERNET_PORTENTA_H7 //#include "PortentaEthernet.h" #include "Ethernet.h" #include "EthernetUdp.h" #warning Using Portenta_Ethernet lib for Portenta_H7. #define SHIELD_TYPE "Ethernet using Portenta_Ethernet Library" #elif USE_ETHERNET_GENERIC #include "Ethernet_Generic.h" #include "EthernetUdp.h" #warning Use Ethernet_Generic lib #define SHIELD_TYPE "W5x00 using Ethernet_Generic Library" #elif USE_ETHERNET #include "Ethernet.h" #include "EthernetUdp.h" #warning Use Ethernet lib #define SHIELD_TYPE "W5x00 using Ethernet Library" #elif USE_ETHERNET_LARGE #include "EthernetLarge.h" #include "EthernetUdp.h" #warning Use EthernetLarge lib #define SHIELD_TYPE "W5x00 using EthernetLarge Library" #elif USE_ETHERNET2 #include "Ethernet2.h" #include "EthernetUdp2.h" #warning Use Ethernet2 lib #define SHIELD_TYPE "W5x00 using Ethernet2 Library" #elif USE_ETHERNET3 #include "Ethernet3.h" #include "EthernetUdp3.h" #warning Use Ethernet3 lib #define SHIELD_TYPE "W5x00 using Ethernet3 Library" #else #define USE_ETHERNET_GENERIC true #include "Ethernet_Generic.h" #include "EthernetUdp.h" #warning Use Ethernet_Generic lib #define SHIELD_TYPE "W5x00 using default Ethernet_Generic Library" #endif // Enter a MAC address and IP address for your controller below. #define NUMBER_OF_MAC 20 byte mac[][NUMBER_OF_MAC] = { { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x01 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x02 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x03 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x04 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x05 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x06 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x07 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x08 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x09 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0A }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0B }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0C }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0D }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0E }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0F }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x10 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x11 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x12 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x13 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x14 }, }; // Select the IP address according to your local network IPAddress ip(192, 168, 2, 222); #endif //defines_h
16,851
C++
.h
399
38.353383
162
0.685426
khoih-prog/MDNS_Generic
37
12
0
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,690
defines.h
khoih-prog_MDNS_Generic/examples/Ethernet/DiscoveringServices/defines.h
/**************************************************************************************************************************** defines.h mDNS library to support mDNS (registering services) and DNS-SD (service discovery). Based on and modified from https://github.com/arduino-libraries/ArduinoMDNS Built by Khoi Hoang https://github.com/khoih-prog/MDNS_Generic Licensed under MIT license Original Author: Georg Kaindl (http://gkaindl.com) This file is part of Arduino EthernetBonjour. EthernetBonjour 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 3 of the License, or (at your option) any later version. EthernetBonjour 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 EthernetBonjour. If not, see <http://www.gnu.org/licenses/>. ***************************************************************************************************************************************/ #ifndef defines_h #define defines_h #define MDNS_DEBUG_PORT Serial // Debug Level from 0 to 4 #define _MDNS_LOGLEVEL_ 1 #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(__SAMD21G18A__) \ || defined(ARDUINO_SAMD_CIRCUITPLAYGROUND_EXPRESS) || defined(__SAMD21E18A__) || defined(__SAMD51__) || defined(__SAMD51J20A__) || defined(__SAMD51J19A__) \ || defined(__SAMD51G19A__) || defined(__SAMD51P19A__) || defined(__SAMD21G18A__) ) #if defined(ETHERNET_USE_SAMD) #undef ETHERNET_USE_SAMD #endif #define ETHERNET_USE_SAMD true #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(ETHERNET_USE_NRF528XX) #undef ETHERNET_USE_NRF528XX #endif #define ETHERNET_USE_NRF528XX true #endif #if ( defined(ARDUINO_SAM_DUE) || defined(__SAM3X8E__) ) #if defined(ETHERNET_USE_SAM_DUE) #undef ETHERNET_USE_SAM_DUE #endif #define ETHERNET_USE_SAM_DUE true #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(ETHERNET_USE_STM32) #undef ETHERNET_USE_STM32 #endif #define ETHERNET_USE_STM32 true #endif #if ( defined(ARDUINO_ARCH_RP2040) || defined(ARDUINO_RASPBERRY_PI_PICO) || defined(ARDUINO_ADAFRUIT_FEATHER_RP2040) || defined(ARDUINO_GENERIC_RP2040) ) #if defined(ETHERNET_USE_RP2040) #undef ETHERNET_USE_RP2040 #endif #define ETHERNET_USE_RP2040 true #if defined(ETHERNET_USE_RPIPICO) #undef ETHERNET_USE_RPIPICO #endif #define ETHERNET_USE_RPIPICO true #endif #if ( defined(ARDUINO_PORTENTA_H7_M7) || defined(ARDUINO_PORTENTA_H7_M4) ) #if defined(BOARD_NAME) #undef BOARD_NAME #endif #if defined(CORE_CM7) #warning Using Portenta H7 M7 core #define BOARD_NAME "PORTENTA_H7_M7" #else #warning Using Portenta H7 M4 core #define BOARD_NAME "PORTENTA_H7_M4" #endif #elif defined(ETHERNET_USE_SAMD) // For SAMD // Default pin 10 to SS/CS #define USE_THIS_SS_PIN 10 #if ( defined(ARDUINO_SAMD_ZERO) && !defined(SEEED_XIAO_M0) ) #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" #define USE_THIS_SS_PIN 10 #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" #ifdef USE_THIS_SS_PIN #undef USE_THIS_SS_PIN #endif #define USE_THIS_SS_PIN A1 #warning define SEEED_XIAO_M0 USE_THIS_SS_PIN == A1 #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(__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 #elif (ETHERNET_USE_SAM_DUE) // Default pin 10 to SS/CS #define USE_THIS_SS_PIN 10 #define BOARD_TYPE "SAM DUE" #elif (ETHERNET_USE_NRF528XX) // Default pin 10 to SS/CS #define USE_THIS_SS_PIN 10 #if defined(NRF52840_FEATHER) #define BOARD_TYPE "NRF52840_FEATHER" #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" #define USE_THIS_SS_PIN 10 // For other boards #elif defined(NRF52840_CIRCUITPLAY) #define BOARD_TYPE "NRF52840_CIRCUITPLAY" #elif defined(NRF52840_CLUE) #define BOARD_TYPE "NRF52840_CLUE" #elif defined(NRF52840_METRO) #define BOARD_TYPE "NRF52840_METRO" #elif defined(NRF52840_PCA10056) #define BOARD_TYPE "NRF52840_PCA10056" #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(ARDUINO_NRF52_ADAFRUIT) #define BOARD_TYPE "ARDUINO_NRF52_ADAFRUIT" #else #define BOARD_TYPE "nRF52 Unknown" #endif #elif ( defined(CORE_TEENSY) ) // Default pin 10 to SS/CS #define USE_THIS_SS_PIN 10 #if defined(__IMXRT1062__) // For Teensy 4.1/4.0 #if defined(ARDUINO_TEENSY41) #define BOARD_TYPE "TEENSY 4.1" // Use true for NativeEthernet Library, false if using other Ethernet libraries #define USE_NATIVE_ETHERNET true #elif defined(ARDUINO_TEENSY40) #define BOARD_TYPE "TEENSY 4.0" #else #define BOARD_TYPE "TEENSY 4.x" #endif #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 #elif (ETHERNET_USE_STM32) #if defined(STM32F0) #define BOARD_TYPE "STM32F0" #elif defined(STM32F1) #define BOARD_TYPE "STM32F1" #elif defined(STM32F2) #define BOARD_TYPE "STM32F2" #elif defined(STM32F3) #define BOARD_TYPE "STM32F3" #elif defined(STM32F4) #define BOARD_TYPE "STM32F4" #elif defined(STM32F7) #define BOARD_TYPE "STM32F7" #elif defined(STM32L0) #define BOARD_TYPE "STM32L0" #elif defined(STM32L1) #define BOARD_TYPE "STM32L1" #elif defined(STM32L4) #define BOARD_TYPE "STM32L4" #elif defined(STM32H7) #define BOARD_TYPE "STM32H7" #elif defined(STM32G0) #define BOARD_TYPE "STM32G0" #elif defined(STM32G4) #define BOARD_TYPE "STM32G4" #elif defined(STM32WB) #define BOARD_TYPE "STM32WB" #elif defined(STM32MP1) #define BOARD_TYPE "STM32MP1" #else #define BOARD_TYPE "STM32 Unknown" #endif #elif (ETHERNET_USE_RP2040 || ETHERNET_USE_RPIPICO) // Default pin 5 (in Mbed) or 17 to SS/CS #if defined(ARDUINO_ARCH_MBED) // For RPI Pico using Arduino Mbed RP2040 core // SCK: GPIO2, MOSI: GPIO3, MISO: GPIO4, SS/CS: GPIO5 #define USE_THIS_SS_PIN 17 #if defined(BOARD_NAME) #undef BOARD_NAME #endif #if defined(ARDUINO_RASPBERRY_PI_PICO) #define BOARD_TYPE "MBED RASPBERRY_PI_PICO" #elif defined(ARDUINO_ADAFRUIT_FEATHER_RP2040) #define BOARD_TYPE "MBED DAFRUIT_FEATHER_RP2040" #elif defined(ARDUINO_GENERIC_RP2040) #define BOARD_TYPE "MBED GENERIC_RP2040" #else #define BOARD_TYPE "MBED Unknown RP2040" #endif #else //#define USING_SPI2 true // For RPI Pico using E. Philhower RP2040 core #if (USING_SPI2) // SCK: GPIO14, MOSI: GPIO15, MISO: GPIO12, SS/CS: GPIO13 for SPI1 #define USE_THIS_SS_PIN 13 #else // SCK: GPIO18, MOSI: GPIO19, MISO: GPIO16, SS/CS: GPIO17 for SPI0 #define USE_THIS_SS_PIN 17 #endif #endif #define SS_PIN_DEFAULT USE_THIS_SS_PIN // For RPI Pico #warning Use RPI-Pico RP2040 architecture #else // For Mega // Default pin 10 to SS/CS #define USE_THIS_SS_PIN 10 // Reduce size for Mega #define SENDCONTENT_P_BUFFER_SZ 512 #define BOARD_TYPE "AVR Mega" #endif #if defined(ARDUINO_BOARD) #define BOARD_NAME ARDUINO_BOARD #elif !defined(BOARD_NAME) #define BOARD_NAME BOARD_TYPE #endif #include <SPI.h> // UIPEthernet, Ethernet_Shield_W5200, EtherCard, EtherSia libraries are not supported // To override the default CS/SS pin. Don't use unless you know exactly which pin to use // You can define here or customize for each board at same place with BOARD_TYPE // Check @ defined(SEEED_XIAO_M0) //#define USE_THIS_SS_PIN 22 //21 //5 //4 //2 //15 // Only one if the following to be true #define USE_ETHERNET_GENERIC true #define USE_ETHERNET_PORTENTA_H7 false #if USE_ETHERNET_PORTENTA_H7 //#include "PortentaEthernet.h" #include "Ethernet.h" #include "EthernetUdp.h" #warning Using Portenta_Ethernet lib for Portenta_H7. #define SHIELD_TYPE "Ethernet using Portenta_Ethernet Library" #elif USE_ETHERNET_GENERIC #include "Ethernet_Generic.h" #include "EthernetUdp.h" #warning Use Ethernet_Generic lib #define SHIELD_TYPE "W5x00 using Ethernet_Generic Library" #elif USE_ETHERNET #include "Ethernet.h" #include "EthernetUdp.h" #warning Use Ethernet lib #define SHIELD_TYPE "W5x00 using Ethernet Library" #elif USE_ETHERNET_LARGE #include "EthernetLarge.h" #include "EthernetUdp.h" #warning Use EthernetLarge lib #define SHIELD_TYPE "W5x00 using EthernetLarge Library" #elif USE_ETHERNET2 #include "Ethernet2.h" #include "EthernetUdp2.h" #warning Use Ethernet2 lib #define SHIELD_TYPE "W5x00 using Ethernet2 Library" #elif USE_ETHERNET3 #include "Ethernet3.h" #include "EthernetUdp3.h" #warning Use Ethernet3 lib #define SHIELD_TYPE "W5x00 using Ethernet3 Library" #else #define USE_ETHERNET_GENERIC true #include "Ethernet_Generic.h" #include "EthernetUdp.h" #warning Use Ethernet_Generic lib #define SHIELD_TYPE "W5x00 using default Ethernet_Generic Library" #endif // Enter a MAC address and IP address for your controller below. #define NUMBER_OF_MAC 20 byte mac[][NUMBER_OF_MAC] = { { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x01 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x02 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x03 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x04 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x05 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x06 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x07 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x08 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x09 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0A }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0B }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0C }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0D }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0E }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0F }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x10 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x11 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x12 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x13 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x14 }, }; // Select the IP address according to your local network IPAddress ip(192, 168, 2, 222); #endif //defines_h
16,853
C++
.h
399
38.358396
162
0.685342
khoih-prog/MDNS_Generic
37
12
0
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,691
multiFileProject.h
khoih-prog_MDNS_Generic/examples/Ethernet/multiFileProject/multiFileProject.h
/**************************************************************************************************************************** multiFileProject.h mDNS library to support mDNS (registering services) and DNS-SD (service discovery). Based on and modified from https://github.com/arduino-libraries/ArduinoMDNS Built by Khoi Hoang https://github.com/khoih-prog/MDNS_Generic Licensed under MIT license *****************************************************************************************************************************/ // To demo how to include files in multi-file Projects #pragma once // Can be included as many times as necessary, without `Multiple Definitions` Linker Error #include "MDNS_Generic.hpp" // Can be included as many times as necessary, without `Multiple Definitions` Linker Error #include "MDNS_Responder.hpp"
851
C++
.h
13
62.846154
126
0.555556
khoih-prog/MDNS_Generic
37
12
0
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,692
defines.h
khoih-prog_MDNS_Generic/examples/Ethernet/multiFileProject/defines.h
/**************************************************************************************************************************** defines.h mDNS library to support mDNS (registering services) and DNS-SD (service discovery). Based on and modified from https://github.com/arduino-libraries/ArduinoMDNS Built by Khoi Hoang https://github.com/khoih-prog/MDNS_Generic Licensed under MIT license Original Author: Georg Kaindl (http://gkaindl.com) This file is part of Arduino EthernetBonjour. EthernetBonjour 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 3 of the License, or (at your option) any later version. EthernetBonjour 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 EthernetBonjour. If not, see <http://www.gnu.org/licenses/>. ***************************************************************************************************************************************/ #ifndef defines_h #define defines_h #define MDNS_DEBUG_PORT Serial // Debug Level from 0 to 4 #define _MDNS_LOGLEVEL_ 1 #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(__SAMD21G18A__) \ || defined(ARDUINO_SAMD_CIRCUITPLAYGROUND_EXPRESS) || defined(__SAMD21E18A__) || defined(__SAMD51__) || defined(__SAMD51J20A__) || defined(__SAMD51J19A__) \ || defined(__SAMD51G19A__) || defined(__SAMD51P19A__) || defined(__SAMD21G18A__) ) #if defined(ETHERNET_USE_SAMD) #undef ETHERNET_USE_SAMD #endif #define ETHERNET_USE_SAMD true #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(ETHERNET_USE_NRF528XX) #undef ETHERNET_USE_NRF528XX #endif #define ETHERNET_USE_NRF528XX true #endif #if ( defined(ARDUINO_SAM_DUE) || defined(__SAM3X8E__) ) #if defined(ETHERNET_USE_SAM_DUE) #undef ETHERNET_USE_SAM_DUE #endif #define ETHERNET_USE_SAM_DUE true #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(ETHERNET_USE_STM32) #undef ETHERNET_USE_STM32 #endif #define ETHERNET_USE_STM32 true #endif #if ( defined(ARDUINO_ARCH_RP2040) || defined(ARDUINO_RASPBERRY_PI_PICO) || defined(ARDUINO_ADAFRUIT_FEATHER_RP2040) || defined(ARDUINO_GENERIC_RP2040) ) #if defined(ETHERNET_USE_RP2040) #undef ETHERNET_USE_RP2040 #endif #define ETHERNET_USE_RP2040 true #if defined(ETHERNET_USE_RPIPICO) #undef ETHERNET_USE_RPIPICO #endif #define ETHERNET_USE_RPIPICO true #endif #if ( defined(ARDUINO_PORTENTA_H7_M7) || defined(ARDUINO_PORTENTA_H7_M4) ) #if defined(BOARD_NAME) #undef BOARD_NAME #endif #if defined(CORE_CM7) #warning Using Portenta H7 M7 core #define BOARD_NAME "PORTENTA_H7_M7" #else #warning Using Portenta H7 M4 core #define BOARD_NAME "PORTENTA_H7_M4" #endif #elif defined(ETHERNET_USE_SAMD) // For SAMD // Default pin 10 to SS/CS #define USE_THIS_SS_PIN 10 #if ( defined(ARDUINO_SAMD_ZERO) && !defined(SEEED_XIAO_M0) ) #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" #define USE_THIS_SS_PIN 10 #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" #ifdef USE_THIS_SS_PIN #undef USE_THIS_SS_PIN #endif #define USE_THIS_SS_PIN A1 #warning define SEEED_XIAO_M0 USE_THIS_SS_PIN == A1 #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(__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 #elif (ETHERNET_USE_SAM_DUE) // Default pin 10 to SS/CS #define USE_THIS_SS_PIN 10 #define BOARD_TYPE "SAM DUE" #elif (ETHERNET_USE_NRF528XX) // Default pin 10 to SS/CS #define USE_THIS_SS_PIN 10 #if defined(NRF52840_FEATHER) #define BOARD_TYPE "NRF52840_FEATHER" #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" #define USE_THIS_SS_PIN 10 // For other boards #elif defined(NRF52840_CIRCUITPLAY) #define BOARD_TYPE "NRF52840_CIRCUITPLAY" #elif defined(NRF52840_CLUE) #define BOARD_TYPE "NRF52840_CLUE" #elif defined(NRF52840_METRO) #define BOARD_TYPE "NRF52840_METRO" #elif defined(NRF52840_PCA10056) #define BOARD_TYPE "NRF52840_PCA10056" #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(ARDUINO_NRF52_ADAFRUIT) #define BOARD_TYPE "ARDUINO_NRF52_ADAFRUIT" #else #define BOARD_TYPE "nRF52 Unknown" #endif #elif ( defined(CORE_TEENSY) ) // Default pin 10 to SS/CS #define USE_THIS_SS_PIN 10 #if defined(__IMXRT1062__) // For Teensy 4.1/4.0 #if defined(ARDUINO_TEENSY41) #define BOARD_TYPE "TEENSY 4.1" // Use true for NativeEthernet Library, false if using other Ethernet libraries #define USE_NATIVE_ETHERNET true #elif defined(ARDUINO_TEENSY40) #define BOARD_TYPE "TEENSY 4.0" #else #define BOARD_TYPE "TEENSY 4.x" #endif #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 #elif (ETHERNET_USE_STM32) #if defined(STM32F0) #define BOARD_TYPE "STM32F0" #elif defined(STM32F1) #define BOARD_TYPE "STM32F1" #elif defined(STM32F2) #define BOARD_TYPE "STM32F2" #elif defined(STM32F3) #define BOARD_TYPE "STM32F3" #elif defined(STM32F4) #define BOARD_TYPE "STM32F4" #elif defined(STM32F7) #define BOARD_TYPE "STM32F7" #elif defined(STM32L0) #define BOARD_TYPE "STM32L0" #elif defined(STM32L1) #define BOARD_TYPE "STM32L1" #elif defined(STM32L4) #define BOARD_TYPE "STM32L4" #elif defined(STM32H7) #define BOARD_TYPE "STM32H7" #elif defined(STM32G0) #define BOARD_TYPE "STM32G0" #elif defined(STM32G4) #define BOARD_TYPE "STM32G4" #elif defined(STM32WB) #define BOARD_TYPE "STM32WB" #elif defined(STM32MP1) #define BOARD_TYPE "STM32MP1" #else #define BOARD_TYPE "STM32 Unknown" #endif #elif (ETHERNET_USE_RP2040 || ETHERNET_USE_RPIPICO) // Default pin 5 (in Mbed) or 17 to SS/CS #if defined(ARDUINO_ARCH_MBED) // For RPI Pico using Arduino Mbed RP2040 core // SCK: GPIO2, MOSI: GPIO3, MISO: GPIO4, SS/CS: GPIO5 #define USE_THIS_SS_PIN 17 #if defined(BOARD_NAME) #undef BOARD_NAME #endif #if defined(ARDUINO_RASPBERRY_PI_PICO) #define BOARD_TYPE "MBED RASPBERRY_PI_PICO" #elif defined(ARDUINO_ADAFRUIT_FEATHER_RP2040) #define BOARD_TYPE "MBED DAFRUIT_FEATHER_RP2040" #elif defined(ARDUINO_GENERIC_RP2040) #define BOARD_TYPE "MBED GENERIC_RP2040" #else #define BOARD_TYPE "MBED Unknown RP2040" #endif #else #define USING_SPI2 false //true // For RPI Pico using E. Philhower RP2040 core #if (USING_SPI2) // SCK: GPIO14, MOSI: GPIO15, MISO: GPIO12, SS/CS: GPIO13 for SPI1 #define USE_THIS_SS_PIN 13 #else // SCK: GPIO18, MOSI: GPIO19, MISO: GPIO16, SS/CS: GPIO17 for SPI0 #define USE_THIS_SS_PIN 17 #endif #endif #define SS_PIN_DEFAULT USE_THIS_SS_PIN // For RPI Pico #warning Use RPI-Pico RP2040 architecture #else // For Mega // Default pin 10 to SS/CS #define USE_THIS_SS_PIN 10 // Reduce size for Mega #define SENDCONTENT_P_BUFFER_SZ 512 #define BOARD_TYPE "AVR Mega" #endif #if defined(ARDUINO_BOARD) #define BOARD_NAME ARDUINO_BOARD #elif !defined(BOARD_NAME) #define BOARD_NAME BOARD_TYPE #endif #include <SPI.h> // UIPEthernet, Ethernet_Shield_W5200, EtherCard, EtherSia libraries are not supported // To override the default CS/SS pin. Don't use unless you know exactly which pin to use // You can define here or customize for each board at same place with BOARD_TYPE // Check @ defined(SEEED_XIAO_M0) //#define USE_THIS_SS_PIN 22 //21 //5 //4 //2 //15 // Only one if the following to be true #define USE_ETHERNET_GENERIC true #define USE_ETHERNET_PORTENTA_H7 false #if USE_ETHERNET_PORTENTA_H7 //#include "PortentaEthernet.h" #include "Ethernet.h" #include "EthernetUdp.h" #warning Using Portenta_Ethernet lib for Portenta_H7. #define SHIELD_TYPE "Ethernet using Portenta_Ethernet Library" #elif USE_ETHERNET_GENERIC #include "Ethernet_Generic.h" #include "EthernetUdp.h" #warning Use Ethernet_Generic lib #define SHIELD_TYPE "W5x00 using Ethernet_Generic Library" #elif USE_ETHERNET #include "Ethernet.h" #include "EthernetUdp.h" #warning Use Ethernet lib #define SHIELD_TYPE "W5x00 using Ethernet Library" #elif USE_ETHERNET_LARGE #include "EthernetLarge.h" #include "EthernetUdp.h" #warning Use EthernetLarge lib #define SHIELD_TYPE "W5x00 using EthernetLarge Library" #elif USE_ETHERNET2 #include "Ethernet2.h" #include "EthernetUdp2.h" #warning Use Ethernet2 lib #define SHIELD_TYPE "W5x00 using Ethernet2 Library" #elif USE_ETHERNET3 #include "Ethernet3.h" #include "EthernetUdp3.h" #warning Use Ethernet3 lib #define SHIELD_TYPE "W5x00 using Ethernet3 Library" #else #define USE_ETHERNET_GENERIC true #include "Ethernet_Generic.h" #include "EthernetUdp.h" #warning Use Ethernet_Generic lib #define SHIELD_TYPE "W5x00 using default Ethernet_Generic Library" #endif // Enter a MAC address and IP address for your controller below. #define NUMBER_OF_MAC 20 byte mac[][NUMBER_OF_MAC] = { { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x01 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x02 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x03 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x04 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x05 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x06 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x07 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x08 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x09 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0A }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0B }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0C }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0D }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0E }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0F }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x10 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x11 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x12 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x13 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x14 }, }; // Select the IP address according to your local network IPAddress ip(192, 168, 2, 222); #endif //defines_h
16,861
C++
.h
399
38.378446
162
0.685313
khoih-prog/MDNS_Generic
37
12
0
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,693
defines.h
khoih-prog_MDNS_Generic/examples/WiFi/WiFiRegisteringServices/defines.h
/**************************************************************************************************************************** defines.h mDNS library to support mDNS (registering services) and DNS-SD (service discovery). Based on and modified from https://github.com/arduino-libraries/ArduinoMDNS Built by Khoi Hoang https://github.com/khoih-prog/MDNS_Generic Licensed under MIT license Original Author: Georg Kaindl (http://gkaindl.com) This file is part of Arduino EthernetBonjour. EthernetBonjour 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 3 of the License, or (at your option) any later version. EthernetBonjour 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 EthernetBonjour. If not, see <http://www.gnu.org/licenses/>. *****************************************************************************************************************************/ #ifndef defines_h #define defines_h #define SYSTEM_ENDIAN _ENDIAN_BIG_ #define MDNS_DEBUG_PORT Serial #define _MDNS_LOGLEVEL_ 4 #define DEBUG_WIFININA_PORT Serial // Debug Level from 0 to 4 #define _WIFININA_LOGLEVEL_ 1 #if defined(ESP32) #define BOARD_TYPE ARDUINO_BOARD #define ESP_getChipId() ((uint32_t)ESP.getEfuseMac()) #define WIFI_NETWORK_ESP true #define WIFI_NETWORK_TYPE WIFI_NETWORK_ESP #elif defined(ESP8266) #error ESP8266 not supported. Please use native ESP8266mDNS library #endif #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(__SAMD21G18A__) \ || defined(ARDUINO_SAMD_CIRCUITPLAYGROUND_EXPRESS) || defined(__SAMD21E18A__) || defined(__SAMD51__) || defined(__SAMD51J20A__) || defined(__SAMD51J19A__) \ || defined(__SAMD51G19A__) || defined(__SAMD51P19A__) || defined(__SAMD21G18A__) ) #if defined(WIFININA_USE_SAMD) #undef WIFININA_USE_SAMD #endif #define WIFININA_USE_SAMD true #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" #define WIFI_NETWORK_WIFI101 true #define WIFI_NETWORK_TYPE WIFI_NETWORK_WIFI101 #elif defined(ARDUINO_SAMD_NANO_33_IOT) #define BOARD_TYPE "SAMD NANO_33_IOT" #define WIFI_NETWORK_WIFININA true #define WIFI_NETWORK_TYPE WIFI_NETWORK_WIFININA #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 #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 // 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) ) && !( defined(ARDUINO_PORTENTA_H7_M7) || defined(ARDUINO_PORTENTA_H7_M4) ) #if defined(WIFININA_USE_STM32) #undef WIFININA_USE_STM32 #endif #define WIFININA_USE_STM32 true #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 // Default pin 5 (in Mbed) or 17 to SS/CS #if defined(ARDUINO_ARCH_MBED) // For RPI Pico using Arduino Mbed RP2040 core // SCK: GPIO2, MOSI: GPIO3, MISO: GPIO4, SS/CS: GPIO5 #define USE_THIS_SS_PIN 5 #if defined(BOARD_NAME) #undef BOARD_NAME #endif #if defined(ARDUINO_NANO_RP2040_CONNECT) #define BOARD_TYPE "MBED NANO_RP2040_CONNECT" #define WIFI_NETWORK_WIFININA true #define WIFI_NETWORK_TYPE WIFI_NETWORK_WIFININA #elif defined(ARDUINO_RASPBERRY_PI_PICO) #define BOARD_TYPE "MBED RASPBERRY_PI_PICO" #elif defined(ARDUINO_ADAFRUIT_FEATHER_RP2040) #define BOARD_TYPE "MBED ADAFRUIT_FEATHER_RP2040" #elif defined(ARDUINO_GENERIC_RP2040) #define BOARD_TYPE "MBED GENERIC_RP2040" #else #define BOARD_TYPE "MBED Unknown RP2040" #endif #else // For RPI Pico using E. Philhower RP2040 core // SCK: GPIO18, MOSI: GPIO19, MISO: GPIO16, SS/CS: GPIO17 #define USE_THIS_SS_PIN 17 #endif #define SS_PIN_DEFAULT USE_THIS_SS_PIN // For RPI Pico #warning Use RPI-Pico RP2040 architecture #endif #if ( defined(ARDUINO_PORTENTA_H7_M7) || defined(ARDUINO_PORTENTA_H7_M4) ) #if defined(BOARD_NAME) #undef BOARD_NAME #endif #if defined(CORE_CM7) #warning Using Portenta H7 M7 core #define BOARD_TYPE "PORTENTA_H7_M7" #else #warning Using Portenta H7 M4 core #define BOARD_TYPE "PORTENTA_H7_M4" #endif #define WIFI_NETWORK_PORTENTA_H7 true #define WIFI_NETWORK_TYPE WIFI_NETWORK_PORTENTA_H7 #elif (ESP32) #define USE_WIFI_NINA false // To use the default WiFi library here #define USE_WIFI_CUSTOM false #endif #ifndef BOARD_NAME #define BOARD_NAME BOARD_TYPE #endif #endif //defines_h
14,600
C++
.h
333
39.750751
162
0.687628
khoih-prog/MDNS_Generic
37
12
0
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,694
defines.h
khoih-prog_MDNS_Generic/examples/WiFi/WiFiDiscoveringServices/defines.h
/**************************************************************************************************************************** defines.h mDNS library to support mDNS (registering services) and DNS-SD (service discovery). Based on and modified from https://github.com/arduino-libraries/ArduinoMDNS Built by Khoi Hoang https://github.com/khoih-prog/MDNS_Generic Licensed under MIT license Original Author: Georg Kaindl (http://gkaindl.com) This file is part of Arduino EthernetBonjour. EthernetBonjour 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 3 of the License, or (at your option) any later version. EthernetBonjour 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 EthernetBonjour. If not, see <http://www.gnu.org/licenses/>. *****************************************************************************************************************************/ #ifndef defines_h #define defines_h #define SYSTEM_ENDIAN _ENDIAN_BIG_ #define MDNS_DEBUG_PORT Serial #define _MDNS_LOGLEVEL_ 1 #define DEBUG_WIFININA_PORT Serial // Debug Level from 0 to 4 #define _WIFININA_LOGLEVEL_ 1 #if defined(ESP32) #define BOARD_TYPE ARDUINO_BOARD #define ESP_getChipId() ((uint32_t)ESP.getEfuseMac()) #define WIFI_NETWORK_ESP true #define WIFI_NETWORK_TYPE WIFI_NETWORK_ESP #elif defined(ESP8266) #error ESP8266 not supported. Please use native ESP8266mDNS library #endif #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(__SAMD21G18A__) \ || defined(ARDUINO_SAMD_CIRCUITPLAYGROUND_EXPRESS) || defined(__SAMD21E18A__) || defined(__SAMD51__) || defined(__SAMD51J20A__) || defined(__SAMD51J19A__) \ || defined(__SAMD51G19A__) || defined(__SAMD51P19A__) || defined(__SAMD21G18A__) ) #if defined(WIFININA_USE_SAMD) #undef WIFININA_USE_SAMD #endif #define WIFININA_USE_SAMD true #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" #define WIFI_NETWORK_WIFI101 true #define WIFI_NETWORK_TYPE WIFI_NETWORK_WIFI101 #elif defined(ARDUINO_SAMD_NANO_33_IOT) #define BOARD_TYPE "SAMD NANO_33_IOT" #define WIFI_NETWORK_WIFININA true #define WIFI_NETWORK_TYPE WIFI_NETWORK_WIFININA #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 #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 // 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) ) && !( defined(ARDUINO_PORTENTA_H7_M7) || defined(ARDUINO_PORTENTA_H7_M4) ) #if defined(WIFININA_USE_STM32) #undef WIFININA_USE_STM32 #endif #define WIFININA_USE_STM32 true #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 // Default pin 5 (in Mbed) or 17 to SS/CS #if defined(ARDUINO_ARCH_MBED) // For RPI Pico using Arduino Mbed RP2040 core // SCK: GPIO2, MOSI: GPIO3, MISO: GPIO4, SS/CS: GPIO5 #define USE_THIS_SS_PIN 5 #if defined(BOARD_NAME) #undef BOARD_NAME #endif #if defined(ARDUINO_NANO_RP2040_CONNECT) #define BOARD_TYPE "MBED NANO_RP2040_CONNECT" #define WIFI_NETWORK_WIFININA true #define WIFI_NETWORK_TYPE WIFI_NETWORK_WIFININA #elif defined(ARDUINO_RASPBERRY_PI_PICO) #define BOARD_TYPE "MBED RASPBERRY_PI_PICO" #elif defined(ARDUINO_ADAFRUIT_FEATHER_RP2040) #define BOARD_TYPE "MBED ADAFRUIT_FEATHER_RP2040" #elif defined(ARDUINO_GENERIC_RP2040) #define BOARD_TYPE "MBED GENERIC_RP2040" #else #define BOARD_TYPE "MBED Unknown RP2040" #endif #else // For RPI Pico using E. Philhower RP2040 core // SCK: GPIO18, MOSI: GPIO19, MISO: GPIO16, SS/CS: GPIO17 #define USE_THIS_SS_PIN 17 #endif #define SS_PIN_DEFAULT USE_THIS_SS_PIN // For RPI Pico #warning Use RPI-Pico RP2040 architecture #endif #if ( defined(ARDUINO_PORTENTA_H7_M7) || defined(ARDUINO_PORTENTA_H7_M4) ) #if defined(BOARD_NAME) #undef BOARD_NAME #endif #if defined(CORE_CM7) #warning Using Portenta H7 M7 core #define BOARD_TYPE "PORTENTA_H7_M7" #else #warning Using Portenta H7 M4 core #define BOARD_TYPE "PORTENTA_H7_M4" #endif #define WIFI_NETWORK_PORTENTA_H7 true #define WIFI_NETWORK_TYPE WIFI_NETWORK_PORTENTA_H7 #elif (ESP32) #define USE_WIFI_NINA false // To use the default WiFi library here #define USE_WIFI_CUSTOM false #endif #ifndef BOARD_NAME #define BOARD_NAME BOARD_TYPE #endif #endif //defines_h
14,600
C++
.h
333
39.750751
162
0.687628
khoih-prog/MDNS_Generic
37
12
0
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,696
MDNS_Generic_Debug.h
khoih-prog_MDNS_Generic/src/MDNS_Generic_Debug.h
/**************************************************************************************************************************** MDNS_Generic_Debug.h mDNS library to support mDNS (registering services) and DNS-SD (service discovery). Based on and modified from https://github.com/arduino-libraries/ArduinoMDNS Built by Khoi Hoang https://github.com/khoih-prog/MDNS_Generic Licensed under MIT license Original Author: Georg Kaindl (http://gkaindl.com) This file is part of Arduino EthernetBonjour. EthernetBonjour 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 3 of the License, or (at your option) any later version. EthernetBonjour 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 EthernetBonjour. If not, see <http://www.gnu.org/licenses/>. Version: 1.4.2 Version Modified By Date Comments ------- ----------- ---------- ----------- 1.0.0 K Hoang 01/08/2020 Initial coding to support W5x00 using Ethernet, EthernetLarge libraries Supported boards: nRF52, STM32, SAMD21/SAMD51, SAM DUE, Mega ... 1.3.0 K Hoang 28/09/2021 Add support to Portenta_H7, using WiFi or Ethernet 1.3.1 K Hoang 10/10/2021 Update `platform.ini` and `library.json` 1.4.0 K Hoang 26/01/2022 Fix `multiple-definitions` linker error 1.4.1 K Hoang 11/04/2022 Use Ethernet_Generic library as default. Support SPI1/SPI2 for RP2040/ESP32 1.4.2 K Hoang 12/10/2022 Fix bugs in UDP length check and in WiFi example *****************************************************************************************************************************/ #ifndef MDNS_Debug_H #define MDNS_Debug_H #include <stdio.h> #ifdef MDNS_DEBUG_PORT #define MDNS_DBG_PORT MDNS_DEBUG_PORT #else #define MDNS_DBG_PORT Serial #endif // Change _MDNS_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 _MDNS_LOGLEVEL_ #define _MDNS_LOGLEVEL_ 0 #endif /////////////////////////////////////// const char MDNS_MARK[] = "[MDNS] "; const char MDNS_SP[] = " "; #define MDNS_PRINT MDNS_DBG_PORT.print #define MDNS_PRINTLN MDNS_DBG_PORT.println #define MDNS_FLUSH MDNS_DBG_PORT.flush #define MDNS_PRINT_MARK MDNS_PRINT(MDNS_MARK) #define MDNS_PRINT_SP MDNS_PRINT(MDNS_SP) /////////////////////////////////////// #define MDNS_LOGERROR(x) if(_MDNS_LOGLEVEL_>0) { MDNS_PRINT_MARK; MDNS_PRINTLN(x); } #define MDNS_LOGERROR0(x) if(_MDNS_LOGLEVEL_>0) { MDNS_PRINT(x); } #define MDNS_LOGERROR1(x,y) if(_MDNS_LOGLEVEL_>0) { MDNS_PRINT_MARK; MDNS_PRINT(x); MDNS_PRINT_SP; MDNS_PRINTLN(y); } #define MDNS_LOGERROR2(x,y,z) if(_MDNS_LOGLEVEL_>0) { MDNS_PRINT_MARK; MDNS_PRINT(x); MDNS_PRINT_SP; MDNS_PRINT(y); MDNS_PRINT_SP; MDNS_PRINTLN(z); } #define MDNS_LOGERROR3(x,y,z,w) if(_MDNS_LOGLEVEL_>0) { MDNS_PRINT_MARK; MDNS_PRINT(x); MDNS_PRINT_SP; MDNS_PRINT(y); MDNS_PRINT_SP; MDNS_PRINT(z); MDNS_PRINT_SP; MDNS_PRINTLN(w); } /////////////////////////////////////// #define MDNS_LOGWARN(x) if(_MDNS_LOGLEVEL_>1) { MDNS_PRINT_MARK; MDNS_PRINTLN(x); } #define MDNS_LOGWARN0(x) if(_MDNS_LOGLEVEL_>1) { MDNS_PRINT(x); } #define MDNS_LOGWARN1(x,y) if(_MDNS_LOGLEVEL_>1) { MDNS_PRINT_MARK; MDNS_PRINT(x); MDNS_PRINT_SP; MDNS_PRINTLN(y); } #define MDNS_LOGWARN2(x,y,z) if(_MDNS_LOGLEVEL_>1) { MDNS_PRINT_MARK; MDNS_PRINT(x); MDNS_PRINT_SP; MDNS_PRINT(y); MDNS_PRINT_SP; MDNS_PRINTLN(z); } #define MDNS_LOGWARN3(x,y,z,w) if(_MDNS_LOGLEVEL_>1) { MDNS_PRINT_MARK; MDNS_PRINT(x); MDNS_PRINT_SP; MDNS_PRINT(y); MDNS_PRINT_SP; MDNS_PRINT(z); MDNS_PRINT_SP; MDNS_PRINTLN(w); } /////////////////////////////////////// #define MDNS_LOGINFO(x) if(_MDNS_LOGLEVEL_>2) { MDNS_PRINT_MARK; MDNS_PRINTLN(x); } #define MDNS_LOGINFO0(x) if(_MDNS_LOGLEVEL_>2) { MDNS_PRINT(x); } #define MDNS_LOGINFO1(x,y) if(_MDNS_LOGLEVEL_>2) { MDNS_PRINT_MARK; MDNS_PRINT(x); MDNS_PRINT_SP; MDNS_PRINTLN(y); } #define MDNS_LOGINFO2(x,y,z) if(_MDNS_LOGLEVEL_>2) { MDNS_PRINT_MARK; MDNS_PRINT(x); MDNS_PRINT_SP; MDNS_PRINT(y); MDNS_PRINT_SP; MDNS_PRINTLN(z); } #define MDNS_LOGINFO3(x,y,z,w) if(_MDNS_LOGLEVEL_>2) { MDNS_PRINT_MARK; MDNS_PRINT(x); MDNS_PRINT_SP; MDNS_PRINT(y); MDNS_PRINT_SP; MDNS_PRINT(z); MDNS_PRINT_SP; MDNS_PRINTLN(w); } /////////////////////////////////////// #define MDNS_LOGDEBUG(x) if(_MDNS_LOGLEVEL_>3) { MDNS_PRINT_MARK; MDNS_PRINTLN(x); } #define MDNS_LOGDEBUG0(x) if(_MDNS_LOGLEVEL_>3) { MDNS_PRINT(x); } #define MDNS_LOGDEBUG1(x,y) if(_MDNS_LOGLEVEL_>3) { MDNS_PRINT_MARK; MDNS_PRINT(x); MDNS_PRINT_SP; MDNS_PRINTLN(y); } #define MDNS_LOGDEBUG2(x,y,z) if(_MDNS_LOGLEVEL_>3) { MDNS_PRINT_MARK; MDNS_PRINT(x); MDNS_PRINT_SP; MDNS_PRINT(y); MDNS_PRINT_SP; MDNS_PRINTLN(z); } #define MDNS_LOGDEBUG3(x,y,z,w) if(_MDNS_LOGLEVEL_>3) { MDNS_PRINT_MARK; MDNS_PRINT(x); MDNS_PRINT_SP; MDNS_PRINT(y); MDNS_PRINT_SP; MDNS_PRINT(z); MDNS_PRINT_SP; MDNS_PRINTLN(w); } /////////////////////////////////////// #endif // MDNS_Debug_H
5,618
C++
.h
77
70.415584
183
0.633805
khoih-prog/MDNS_Generic
37
12
0
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,701
MDNS_Generic.h
khoih-prog_MDNS_Generic/src/MDNS_Generic.h
/**************************************************************************************************************************** MDNS_Generic.h mDNS library to support mDNS (registering services) and DNS-SD (service discovery). Based on and modified from https://github.com/arduino-libraries/ArduinoMDNS Built by Khoi Hoang https://github.com/khoih-prog/MDNS_Generic Licensed under MIT license Original Author: Georg Kaindl (http://gkaindl.com) This file is part of Arduino EthernetBonjour. EthernetBonjour 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 3 of the License, or (at your option) any later version. EthernetBonjour 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 EthernetBonjour. If not, see <http://www.gnu.org/licenses/>. Version: 1.4.2 Version Modified By Date Comments ------- ----------- ---------- ----------- 1.0.0 K Hoang 01/08/2020 Initial coding to support W5x00 using Ethernet, EthernetLarge libraries Supported boards: nRF52, STM32, SAMD21/SAMD51, SAM DUE, Mega ... 1.3.0 K Hoang 28/09/2021 Add support to Portenta_H7, using WiFi or Ethernet 1.3.1 K Hoang 10/10/2021 Update `platform.ini` and `library.json` 1.4.0 K Hoang 26/01/2022 Fix `multiple-definitions` linker error 1.4.1 K Hoang 11/04/2022 Use Ethernet_Generic library as default. Support SPI1/SPI2 for RP2040/ESP32 1.4.2 K Hoang 12/10/2022 Fix bugs in UDP length check and in WiFi example *****************************************************************************************************************************/ #ifndef __MDNS_GENERIC_H__ #define __MDNS_GENERIC_H__ #include "MDNS_Generic.hpp" #include "MDNS_Generic_Impl.h" #endif // __MDNS_GENERIC_H__
2,186
C++
.h
31
66.419355
133
0.636151
khoih-prog/MDNS_Generic
37
12
0
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,702
MDNS_Responder.h
khoih-prog_MDNS_Generic/src/MDNS_Responder.h
/**************************************************************************************************************************** MDNS_Responder.h mDNS library to support mDNS (registering services) and DNS-SD (service discovery). Based on and modified from https://github.com/arduino-libraries/ArduinoMDNS Built by Khoi Hoang https://github.com/khoih-prog/MDNS_Generic Licensed under MIT license Original Author: Georg Kaindl (http://gkaindl.com) This file is part of Arduino EthernetBonjour. EthernetBonjour 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 3 of the License, or (at your option) any later version. EthernetBonjour 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 EthernetBonjour. If not, see <http://www.gnu.org/licenses/>. Version: 1.4.2 Version Modified By Date Comments ------- ----------- ---------- ----------- 1.0.0 K Hoang 01/08/2020 Initial coding to support W5x00 using Ethernet, EthernetLarge libraries Supported boards: nRF52, STM32, SAMD21/SAMD51, SAM DUE, Mega ... 1.3.0 K Hoang 28/09/2021 Add support to Portenta_H7, using WiFi or Ethernet 1.3.1 K Hoang 10/10/2021 Update `platform.ini` and `library.json` 1.4.0 K Hoang 26/01/2022 Fix `multiple-definitions` linker error 1.4.1 K Hoang 11/04/2022 Use Ethernet_Generic library as default. Support SPI1/SPI2 for RP2040/ESP32 1.4.2 K Hoang 12/10/2022 Fix bugs in UDP length check and in WiFi example *****************************************************************************************************************************/ // Port of CC3000 MDNS Responder to WINC1500. // Author: Tony DiCola // // This MDNSResponder class implements just enough MDNS functionality to respond // to name requests, for example 'foo.local'. This does not implement any other // MDNS or Bonjour functionality like services, etc. // // Copyright (c) 2016 Adafruit Industries. 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 MDNS_RESPONDER_H #define MDNS_RESPONDER_H #include "MDNS_Responder.hpp" #include "MDNS_Responder_Impl.h" #endif
3,259
C++
.h
53
58.698113
133
0.684623
khoih-prog/MDNS_Generic
37
12
0
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,706
mod.cpp
zhkj-liuxiaohua_BDSNetRunner/BDSNetRunner/mod.cpp
#include "mod.h" #include "THook.h" #include <stdio.h> #include <iostream> #include <shlwapi.h> #include "BDS.hpp" #include "Component.h" #include <thread> #include <map> #include <fstream> #include <mscoree.h> #include <metahost.h> #include "json/json.h" #include "tick/tick.h" #include "GUI/SimpleForm.h" #include <mutex> #include "commands/commands.h" #include "scoreboard/scoreboard.hpp" #pragma comment(lib, "mscoree.lib") #pragma comment(lib, "Shlwapi.lib") // 当前插件平台版本号 static const wchar_t* VERSION = L"1.16.100.4"; static const wchar_t* ISFORCOMMERCIAL = L"1"; static bool netregok = false; static void releaseNetFramework(); void** getOriginalData(void*); HookErrorCode mTHook2(RVA, void*); static std::mutex mleftlock; // 调试信息 template<typename T> static void PR(T arg) { #ifndef RELEASED std::cout << arg << std::endl; #endif // !RELEASED } // 转换Json对象为字符串 static std::string toJsonString(Json::Value v) { Json::StreamWriterBuilder w; std::ostringstream os; std::unique_ptr<Json::StreamWriter> jsonWriter(w.newStreamWriter()); jsonWriter->write(v, &os); return std::string(os.str()); } // 转换字符串为Json对象 static Json::Value toJson(std::string s) { Json::Value jv; Json::CharReaderBuilder r; JSONCPP_STRING errs; std::unique_ptr<Json::CharReader> const jsonReader(r.newCharReader()); bool res = jsonReader->parse(s.c_str(), s.c_str() + s.length(), &jv, &errs); if (!res || !errs.empty()) { PR(u8"JSON转换失败。。" + errs); } return jv; } // UTF-8 转 GBK static std::string UTF8ToGBK(const char* strUTF8) { int len = MultiByteToWideChar(CP_UTF8, 0, strUTF8, -1, NULL, 0); wchar_t* wszGBK = new wchar_t[(size_t)len + 1]; memset(wszGBK, 0, (size_t)len * 2 + 2); MultiByteToWideChar(CP_UTF8, 0, strUTF8, -1, wszGBK, len); len = WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, NULL, 0, NULL, NULL); char* szGBK = new char[(size_t)len + 1]; memset(szGBK, 0, (size_t)len + 1); WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, szGBK, len, NULL, NULL); std::string strTemp(szGBK); if (wszGBK) delete[] wszGBK; if (szGBK) delete[] szGBK; return strTemp; } static std::wstring toGBKString(std::string s) { int len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), (int)s.length(), NULL, 0); WCHAR* w_str = new WCHAR[(size_t)len + 1]{ 0 }; MultiByteToWideChar(CP_ACP, 0, s.c_str(), (int)s.length(), w_str, len); auto gbkstr = std::wstring(w_str); delete[] w_str; return gbkstr; } // GBK 转 UTF-8 static std::string GBKToUTF8(const char* strGBK) { std::string strOutUTF8 = ""; WCHAR* str1; int n = MultiByteToWideChar(CP_ACP, 0, strGBK, -1, NULL, 0); str1 = new WCHAR[n]; MultiByteToWideChar(CP_ACP, 0, strGBK, -1, str1, n); n = WideCharToMultiByte(CP_UTF8, 0, str1, -1, NULL, 0, NULL, NULL); char* str2 = new char[n]; WideCharToMultiByte(CP_UTF8, 0, str1, -1, str2, n, NULL, NULL); strOutUTF8 = str2; delete[]str1; str1 = NULL; delete[]str2; str2 = NULL; return strOutUTF8; } static std::string toUTF8String(std::wstring s) { int iSize = WideCharToMultiByte(CP_ACP, 0, s.c_str(), -1, NULL, 0, NULL, NULL); char* uc = new char[(size_t)(iSize) * 3 + 1]{ 0 }; WideCharToMultiByte(CP_ACP, 0, s.c_str(), -1, uc, iSize, NULL, NULL); auto utf8str = std::string(uc); delete[] uc; return utf8str; } // 自动复制字符 static void autoByteCpy(char** d, const char* s) { if (d) { VA l = strlen(s); if (*d) { delete (*d); } *d = new char[l + 1]{ 0 }; strcpy_s(*d, l + 1, s); } } static VA p_spscqueue = 0; static VA p_level = 0; static VA p_ServerNetworkHandle = 0; static VA p_jsen = 0; static HMODULE GetSelfModuleHandle() { MEMORY_BASIC_INFORMATION mbi; return ((::VirtualQuery(GetSelfModuleHandle, &mbi, sizeof(mbi)) != 0) ? (HMODULE)mbi.AllocationBase : NULL); } // 获取自身DLL路径 static std::wstring GetDllPathandVersion() { std::ifstream file; wchar_t curDir[256]{ 0 }; GetModuleFileName(GetSelfModuleHandle(), curDir, 256); std::wstring dllandVer = std::wstring(curDir); dllandVer = dllandVer + std::wstring(L",") + std::wstring(VERSION); if (netregok) dllandVer = dllandVer + std::wstring(L",") + std::wstring(ISFORCOMMERCIAL); return dllandVer; } std::unordered_map<std::string, std::vector<void*>*> beforecallbacks, aftercallbacks; // 执行回调 static bool runCscode(std::string key, ActMode mode, Events& eventData) { auto& funcs = (mode == ActMode::BEFORE) ? beforecallbacks : aftercallbacks; auto dv = funcs[key]; bool ret = true; if (dv) { if (dv->size() > 0) { for (auto& func : *dv) { try { ret = ret && ((bool(*)(Events))func)(eventData); } catch (...) { PR("[CSR] Event callback exception."); } } } } return ret; } static ACTEVENT ActEvent; static std::unordered_map<std::string, VA*> sListens; // 监听列表 static std::unordered_map<std::string, bool> isListened; // 是否已监听 static bool addListener(std::string key, ActMode mode, bool(*func)(Events)) { auto& funcs = (mode == ActMode::BEFORE) ? beforecallbacks : aftercallbacks; if (key != "" && func != NULL) { if (!isListened[key]) { // 动态挂载hook监听 VA* syms = sListens[key]; int hret = 0; if (syms) { for (VA i = 0, len = syms[0]; i < len; ++i) { // 首数为sym长度 hret += (int)mTHook2((RVA)syms[(i * 2) + 1], (void*)syms[(i * 2) + 2]); // 第一数为sym,第二数为func } } if (hret) { PR("[CSR] Some hooks wrong at event setting."); } isListened[key] = true; // 只挂载一次 } auto dv = funcs[key]; if (dv == NULL) { dv = new std::vector<void*>(); funcs[key] = dv; } if (std::find(dv->begin(), dv->end(), func) == dv->end()) { // 未找到已有函数,加入回调 dv->push_back(func); return true; } } return false; } static void remove_v2(std::vector<void*>* v, void* val) { v->erase(std::remove(v->begin(), v->end(), val), v->end()); } static bool removeListener(std::string key, ActMode mode, bool(*func)(Events)) { auto& funcs = (mode == ActMode::BEFORE) ? beforecallbacks : aftercallbacks; if (key != "" && func != NULL) { auto dv = funcs[key]; if (dv != NULL) { bool exi = std::find(dv->begin(), dv->end(), func) != dv->end(); if (exi) remove_v2(dv, func); return exi; } } return false; } bool addBeforeActListener(const char* key, bool(*func)(Events)) { return addListener(key, ActMode::BEFORE, func); } bool addAfterActListener(const char* key, bool(*func)(Events)) { return addListener(key, ActMode::AFTER, func); } bool removeBeforeActListener(const char* key, bool(*func)(Events)) { return removeListener(key, ActMode::BEFORE, func); } bool removeAfterActListener(const char* key, bool(*func)(Events)) { return removeListener(key, ActMode::AFTER, func); } void postTick(void(*m)()) { safeTick(m); } static std::unordered_map<std::string, void*> shareData; void setSharePtr(const char* key, void* func) { shareData[key] = func; } void* getSharePtr(const char* key) { return shareData[key]; } void* removeSharePtr(const char* key) { std::string k = std::string(key); void* x = shareData[k]; shareData.erase(k); return x; } // 维度ID转换为中文字符 static std::string toDimenStr(int dimensionId) { switch (dimensionId) { case 0:return u8"主世界"; case 1:return u8"地狱"; case 2:return u8"末地"; default: break; } return u8"未知维度"; } static VA regHandle = 0; struct CmdDescriptionFlags { std::string description; char level; char flag1; char flag2; }; static std::unordered_map<std::string, std::unique_ptr<CmdDescriptionFlags>> cmddescripts; // 函数名:setCommandDescribeEx // 功能:设置一个全局指令说明 // 参数个数:2个 // 参数类型:字符串,字符串,整型,整型,整型 // 参数详解:cmd - 命令,description - 命令说明,level - 执行要求等级,flag1 - 命令类型1, flag2 - 命令类型2 // 备注:延期注册的情况,可能不会改变客户端界面 void setCommandDescribeEx(const char* cmd, const char* description, char level, char flag1, char flag2) { auto strcmd = GBKToUTF8(cmd); if (strcmd.length()) { auto flgs = std::make_unique<CmdDescriptionFlags>(); flgs->description = GBKToUTF8(description); flgs->level = level; flgs->flag1 = flag1; flgs->flag2 = flag2; cmddescripts[strcmd] = std::move(flgs); if (regHandle) { std::string c = strcmd; auto ct = GBKToUTF8(description); SYMCALL(VA, MSSYM_MD5_8574de98358ff66b5a913417f44dd706, regHandle, &c, ct.c_str(), level, flag1, flag2); } } } // 函数名:runcmd // 功能:执行后台指令 // 参数个数:1个 // 参数类型:字符串 // 参数详解:cmd - 语法正确的MC指令 // 返回值:是否正常执行 bool runcmd(const char* cmd) { auto strcmd = GBKToUTF8(cmd); if (p_spscqueue != 0) { if (p_level) { auto fr = [strcmd]() { SYMCALL(bool, MSSYM_MD5_b5c9e566146b3136e6fb37f0c080d91e, p_spscqueue, strcmd); }; safeTick(fr); return true; } } return false; } // 标准输出句柄常量 static const VA STD_COUT_HANDLE = SYM_OBJECT(VA, MSSYM_B2UUA3impB2UQA4coutB1AA3stdB2AAA23VB2QDA5basicB1UA7ostreamB1AA2DUB2QDA4charB1UA6traitsB1AA1DB1AA3stdB3AAAA11B1AA1A); // 函数名:logout // 功能:发送一条命令输出消息(可被拦截) // 参数个数:1个 // 参数类型:字符串 // 参数详解:cmdout - 待发送的命令输出字符串 void logout(const char* cmdout) { std::string strout = GBKToUTF8(cmdout) + "\n"; SYMCALL(VA, MSSYM_MD5_b5f2f0a753fc527db19ac8199ae8f740, STD_COUT_HANDLE, strout.c_str(), strout.length()); } static std::unordered_map<std::string, Player*> onlinePlayers; static std::unordered_map<Player*, bool> playerSign; // 函数名:getOnLinePlayers // 功能:获取在线玩家列表 // 参数个数:0个 // 返回值:玩家列表的Json字符串 std::string getOnLinePlayers() { Json::Value rt; Json::Value jv; mleftlock.lock(); for (auto& op : playerSign) { Player* p = op.first; if (op.second) { jv["playername"] = p->getNameTag(); jv["uuid"] = p->getUuid()->toString(); jv["xuid"] = p->getXuid(p_level); jv["playerptr"] = (VA)p; rt.append(jv); } } mleftlock.unlock(); return rt.isNull() ? "" : std::string(rt.toStyledString().c_str()); } // 函数名:getItemRawname // 功能:获取物品原始标识字符 // 参数个数:1个 // 参数类型:整型 // 参数详解:id - 物品id // 返回值:物品名称 std::string getItemRawname(int id) { std::string rawname = Item::getRawNameFromId(id); return rawname; } #if MODULE_KENGWANG // 函数名:setServerMotd // 功能:设置服务器的显示名信息 // 参数个数:2个 // 参数类型:字符串,布尔型 // 参数详解:motd - 新服务器显示名信息,isShow - 是否公开显示 // (注:服务器名称加载时机在地图完成载入之后) bool setServerMotd(const char* motd, bool isShow) { if (p_ServerNetworkHandle) { std::string nmotd = GBKToUTF8(motd); SYMCALL(VA, MSSYM_MD5_21204897709106ba1d290df17fead479, p_ServerNetworkHandle, &nmotd, isShow); return true; } return false; } #endif // 函数名:reNameByUuid // 功能:重命名一个指定的玩家名 // 参数个数:2个 // 参数类型:字符串,字符串 // 参数详解:uuid - 在线玩家的uuid字符串,newName - 新的名称 // 返回值:是否命名成功 // (备注:该函数可能不会变更客户端实际显示名) bool reNameByUuid(const char* cuuid, const char* cnewName) { bool ret = false; std::string uuid = std::string(cuuid); std::string newName = GBKToUTF8(cnewName); Player* taget = onlinePlayers[uuid]; if (playerSign[taget]) { auto fr = [uuid, newName]() { Player* p = onlinePlayers[uuid]; if (playerSign[p]) { p->reName(newName); } }; safeTick(fr); ret = true; } return ret; } // 函数名:addPlayerItem // 功能:增加玩家一个物品 // 参数个数:4个 // 参数类型:字符串 // 参数详解:uuid - 在线玩家的uuid字符串,id - 物品id值,aux - 物品特殊值,count - 数量 // 返回值:是否增加成功 // (备注:特定条件下可能不会变更游戏内实际物品) bool addPlayerItem(const char* uuid, int id, short aux, char count) { Player* p = onlinePlayers[uuid]; bool ret = false; if (playerSign[p]) { std::string suuid = uuid; auto fr = [suuid, id, aux, count]() { Player* p = onlinePlayers[suuid]; if (playerSign[p]) { ItemStack x; x.getFromId(id, aux, count); p->addItem((VA)&x); p->updateInventory(); } }; safeTick(fr); ret = true; } return ret; } // 在JSON数据中附上玩家基本信息 static void addPlayerJsonInfo(Json::Value& jv, Player* p) { if (p) { jv["playername"] = p->getNameTag(); int did = p->getDimensionId(); jv["dimensionid"] = did; jv["dimension"] = toDimenStr(did); jv["isstand"] = p->isStand(); jv["XYZ"] = toJson(p->getPos()->toJsonString()); jv["playerptr"] = (VA)p; } } // 函数名:selectPlayer // 功能:查询在线玩家基本信息 // 参数个数:1个 // 参数类型:字符串 // 参数详解:uuid - 在线玩家的uuid字符串 // 返回值:玩家基本信息json字符串 std::string selectPlayer(const char* uuid) { Player* p = onlinePlayers[uuid]; if (playerSign[p]) { mleftlock.lock(); Json::Value jv; addPlayerJsonInfo(jv, p); jv["uuid"] = p->getUuid()->toString(); jv["xuid"] = p->getXuid(p_level); #if (COMMERCIAL) jv["health"] = p->getAttr("health"); #endif mleftlock.unlock(); return std::string(jv.toStyledString().c_str()); } return ""; } // 函数名:talkAs // 功能:模拟玩家发送一个文本 // 参数个数:2个 // 参数类型:字符串,字符串 // 参数详解:uuid - 在线玩家的uuid字符串,msg - 待模拟发送的文本 // 返回值:是否发送成功 bool talkAs(const char* uuid, const char* msg) { Player* p = onlinePlayers[uuid]; if (playerSign[p]) { // IDA ServerNetworkHandler::handle, https://github.com/NiclasOlofsson/MiNET/blob/master/src/MiNET/MiNET/Net/MCPE%20Protocol%20Documentation.md std::string suuid = uuid; std::string txt = GBKToUTF8(msg); auto fr = [suuid, txt]() { Player* p = onlinePlayers[suuid]; if (playerSign[p]) { std::string n = p->getNameTag(); VA nid = p->getNetId(); VA tpk; TextPacket sec; SYMCALL(VA, MSSYM_B1QE12createPacketB1AE16MinecraftPacketsB2AAA2SAB1QA2AVB2QDA6sharedB1UA3ptrB1AA7VPacketB3AAAA3stdB2AAE20W4MinecraftPacketIdsB3AAAA1Z, &tpk, 9); *(char*)(tpk + 40) = 1; memcpy((void*)(tpk + 48), &n, sizeof(n)); memcpy((void*)(tpk + 80), &txt, sizeof(txt)); SYMCALL(VA, MSSYM_B1QA6handleB1AE20ServerNetworkHandlerB2AAE26UEAAXAEBVNetworkIdentifierB2AAE14AEBVTextPacketB3AAAA1Z, p_ServerNetworkHandle, nid, tpk); } }; safeTick(fr); return true; } return false; } // 函数名:runcmdAs // 功能:模拟玩家执行一个指令 // 参数个数:2个 // 参数类型:字符串,字符串 // 参数详解:uuid - 在线玩家的uuid字符串,cmd - 待模拟执行的指令 // 返回值:是否发送成功 bool runcmdAs(const char* uuid, const char* cmd) { Player* p = onlinePlayers[uuid]; if (playerSign[p]) { std::string suuid = uuid; std::string scmd = GBKToUTF8(cmd); auto fr = [suuid, scmd]() { Player* p = onlinePlayers[suuid]; if (playerSign[p]) { VA nid = p->getNetId(); VA tpk; CommandRequestPacket src; SYMCALL(VA, MSSYM_B1QE12createPacketB1AE16MinecraftPacketsB2AAA2SAB1QA2AVB2QDA6sharedB1UA3ptrB1AA7VPacketB3AAAA3stdB2AAE20W4MinecraftPacketIdsB3AAAA1Z, &tpk, 76); memcpy((void*)(tpk + 40), &scmd, sizeof(scmd)); SYMCALL(VA, MSSYM_B1QA6handleB1AE20ServerNetworkHandlerB2AAE26UEAAXAEBVNetworkIdentifierB2AAE24AEBVCommandRequestPacketB3AAAA1Z, p_ServerNetworkHandle, nid, tpk); } }; safeTick(fr); return true; } return false; } // 函数名:disconnectClient // 功能:断开一个玩家的连接 // 参数个数:2个 // 参数类型:字符串,字符串 // 参数详解:uuid - 在线玩家的uuid字符串,tips - 断开提示(设空值则为默认值) // 返回值:是否发送成功 bool disconnectClient(const char* uuid, const char* tips) { Player* p = onlinePlayers[uuid]; if (playerSign[p]) { std::string suuid = uuid; std::string stips = "disconnectionScreen.disconnected"; if (tips) { auto s = GBKToUTF8(tips); if (s.length()) stips = s; } auto fr = [suuid, stips]() { Player* p = onlinePlayers[suuid]; if (playerSign[p]) { VA nid = p->getNetId(); SYMCALL(VA, MSSYM_MD5_389e602d185eac21ddcc53a5bb0046ee, p_ServerNetworkHandle, nid, 0, stips, 0); } }; safeTick(fr); return true; } return false; } // 函数名:sendText // 功能:发送一个文本给指定玩家 // 参数个数:2个 // 参数类型:字符串,字符串 // 参数详解:uuid - 在线玩家的uuid字符串,txt - 聊天框文本 // 返回值:是否发送成功 bool sendText(const char* uuid, const char* txt) { Player* p = onlinePlayers[uuid]; if (playerSign[p]) { std::string suuid = uuid; std::string stxt = ""; if (txt) { auto s = GBKToUTF8(txt); if (s.length()) stxt = s; } if (stxt.length()) { auto fr = [suuid, stxt]() { Player* p = onlinePlayers[suuid]; if (playerSign[p]) { std::string n = p->getNameTag(); VA nid = p->getNetId(); VA tpk; TextPacket sec; SYMCALL(VA, MSSYM_B1QE12createPacketB1AE16MinecraftPacketsB2AAA2SAB1QA2AVB2QDA6sharedB1UA3ptrB1AA7VPacketB3AAAA3stdB2AAE20W4MinecraftPacketIdsB3AAAA1Z, &tpk, 9); *(char*)(tpk + 40) = 0; *(std::string*)(tpk + 48) = n; *(std::string*)(tpk + 80) = stxt; p->sendPacket(tpk); } }; safeTick(fr); return true; } } return false; } // 自增长临时脚本ID static VA tmpjsid = 0; // 获取临时脚本ID值,调用一次自增长一次 static VA getTmpJsId() { return tmpjsid++; } // 函数名:JSErunScript // 功能:请求执行一段行为包脚本 // 参数个数:2个 // 参数类型:字符串,函数指针 // 参数详解:content - 脚本文本,callb - 执行结果回调函数 // (注:每次调用都会新增脚本环境,请避免多次重复调用此方法) void JSErunScript(const char* content, void(*callb)(bool)) { if (p_jsen) { std::string uc = GBKToUTF8(content); auto fn = [uc, callb]() { std::string name = u8"CSR_tmpscript_" + std::to_string(getTmpJsId()); std::string rfcontent = u8"(function(){\n" + uc + u8"\n}())"; auto v32 = GetModuleHandleW(NULL) + 1611876; bool ret = ((bool(*)(VA, std::string&, std::string&))v32)( p_jsen, name, rfcontent); if (callb != nullptr) callb(ret); }; safeTick(fn); } else { if (callb != nullptr) callb(false); } } struct JSON_VALUE { VA fill[2]{ 0 }; public: JSON_VALUE() { SYMCALL(VA, MSSYM_B2QQA60ValueB1AA4JsonB2AAA4QEAAB1AE11W4ValueTypeB1AA11B2AAA1Z, this, 1); } ~JSON_VALUE() { SYMCALL(VA, MSSYM_B2QQA61ValueB1AA4JsonB2AAA4QEAAB1AA2XZ, this); } }; struct ScriptEventData { VA vtabl; std::string eventName; }; struct CustomScriptEventData : ScriptEventData { JSON_VALUE mdata; }; // 函数名:JSEfireCustomEvent // 功能:请求发送一个自定义行为包脚本事件广播 // 参数个数:3个 // 参数类型:字符串,字符串,函数指针 // 参数详解:name - 自定义事件名称(不得以minecraft:开头),jdata - JSON格式文本,callb - 执行结果回调函数 void JSEfireCustomEvent(const char* name, const char* jdata, void(*callb)(bool)) { if (p_jsen) { std::string unanme = GBKToUTF8(name); std::string ujdata = GBKToUTF8(jdata); auto fn = [unanme, ujdata, callb]() { CustomScriptEventData edata; auto v13 = GetModuleHandleW(NULL) + 6448064; edata.vtabl = (VA)v13; edata.eventName = unanme; auto v5 = GetModuleHandleW(NULL); ((void(*)(void*, const char*))(v5 + 1385528))(&edata.mdata, ujdata.c_str()); bool ret = ((bool(*)(VA, VA))(v5 + 2818436))(p_jsen, (VA)&edata); if (callb != nullptr) { callb(ret); } }; safeTick(fn); } else { if (callb != nullptr) { callb(false); } } } // 判断指针是否为玩家列表中指针 static bool checkIsPlayer(void* p) { return playerSign[(Player*)p]; } static std::map<unsigned, bool> fids; // 获取一个未被使用的基于时间秒数的id static unsigned getFormId() { unsigned id = (unsigned)(time(0) + rand()); do { ++id; } while (id == 0 || fids[id]); fids[id] = true; return id; } // 函数名:releaseForm // 功能:放弃一个表单 // 参数个数:1个 // 参数类型:整型 // 参数详解:formid - 表单id // 返回值:是否释放成功 //(备注:已被接收到的表单会被自动释放) bool releaseForm(unsigned fid) { if (fids[fid]) { fids.erase(fid); return true; } return false; } // 发送一个SimpleForm的表单数据包 static unsigned sendForm(std::string uuid, std::string str) { unsigned fid = getFormId(); // 此处自主创建包 auto fr = [uuid, fid, str]() { Player* p = onlinePlayers[uuid]; if (playerSign[p]) { VA tpk; ModalFormRequestPacket sec; SYMCALL(VA, MSSYM_B1QE12createPacketB1AE16MinecraftPacketsB2AAA2SAB1QA2AVB2QDA6sharedB1UA3ptrB1AA7VPacketB3AAAA3stdB2AAE20W4MinecraftPacketIdsB3AAAA1Z, &tpk, 100); *(VA*)(tpk + 40) = fid; *(std::string*)(tpk + 48) = str; p->sendPacket(tpk); } }; safeTick(fr); return fid; } // 函数名:sendSimpleForm // 功能:向指定的玩家发送一个简单表单 // 参数个数:4个 // 参数类型:字符串,字符串,字符串,字符串 // 参数详解:uuid - 在线玩家的uuid字符串,title - 表单标题,content - 内容,buttons - 按钮文本数组字符串 // 返回值:创建的表单id,为 0 表示发送失败 UINT sendSimpleForm(char* uuid, char* title, char* content, char* buttons) { Player* p = onlinePlayers[uuid]; if (!playerSign[p]) return 0; auto stitle = GBKToUTF8(title); auto scontent = GBKToUTF8(content); auto sbuttons = GBKToUTF8(buttons); Json::Value bts; Json::Value ja = toJson(sbuttons); for (unsigned i = 0; i < ja.size(); i++) { Json::Value bt; bt["text"] = ja[i]; bts.append(bt); } if (bts.isNull()) bts = toJson("[]"); std::string str = createSimpleFormString(stitle, scontent, bts); return sendForm(uuid, str); } // 函数名:sendModalForm // 功能:向指定的玩家发送一个模式对话框 // 参数个数:5个 // 参数类型:字符串,字符串,字符串,字符串,字符串 // 参数详解:uuid - 在线玩家的uuid字符串,title - 表单标题,content - 内容,button1 按钮1标题(点击该按钮selected为true),button2 按钮2标题(点击该按钮selected为false) // 返回值:创建的表单id,为 0 表示发送失败 UINT sendModalForm(char* uuid, char* title, char* content, char* button1, char* button2) { Player* p = onlinePlayers[uuid]; if (!playerSign[p]) return 0; auto utitle = GBKToUTF8(title); auto ucontent = GBKToUTF8(content); auto ubutton1 = GBKToUTF8(button1); auto ubutton2 = GBKToUTF8(button2); std::string str = createModalFormString(utitle, ucontent, ubutton1, ubutton2); return sendForm(uuid, str); } // 函数名:sendCustomForm // 功能:向指定的玩家发送一个自定义表单 // 参数个数:2个 // 参数类型:字符串,字符串 // 参数详解:uuid - 在线玩家的uuid字符串,json - 自定义表单的json字符串(要使用自定义表单类型,参考nk、pm格式或minebbs专栏) // 返回值:创建的表单id,为 0 表示发送失败 UINT sendCustomForm(char* uuid, char* json) { Player* p = onlinePlayers[uuid]; if (!playerSign[p]) return 0; auto ujson = GBKToUTF8(json); return sendForm(uuid, ujson); } #if (MODULE_05007) extern Scoreboard* scoreboard; // 函数名:getscorebroardValue // 功能:获取指定玩家指定计分板上的数值 // 参数个数:2个 // 参数类型:字符串,字符串 // 参数详解:uuid - 在线玩家的uuid字符串,objname - 计分板登记的名称 // 返回值:获取的目标值,若目标不存在则发信一条创建指令 int getscoreboardValue(const char* uuid, const char* objname) { Player* p = onlinePlayers[uuid]; if (!playerSign[p]) return 0; auto oname = GBKToUTF8(objname); return getscoreboard(p, oname); } // 函数名:getscorebroardValue // 功能:设置指定玩家指定计分板上的数值 // 参数个数:3个 // 参数类型:字符串,字符串,数值 // 参数详解:uuid - 在线玩家的uuid字符串,objname - 计分板登记的名称,count - 待设置的值 // 返回值:是否设置成功,若目标不存在则发信一条创建指令及设置分数指令 bool setscoreboardValue(const char* uuid, const char* objname, int count) { Player* p = onlinePlayers[uuid]; if (!playerSign[p]) return false; auto oname = GBKToUTF8(objname); return setscoreboard(p, oname, count); } #endif // 找到一个ID static bool findScoreboardId(__int64 id, void* outid) { struct RDATA { VA fill[3]; }; std::vector<RDATA> rs; auto v5 = GetModuleHandleW(0); ((VA(*)(VA, VA))(v5 + 4689216))((VA)scoreboard, (VA)&rs); bool finded = false; if (rs.size() > 0) { for (auto& x : rs) { if (x.fill[2] == id) { memcpy(outid, &(x.fill[2]), 16); finded = true; break; } } } return finded; } // 函数名:getscoreById // 功能:获取指定ID对应于计分板上的数值 // 参数个数:2个 // 参数类型:长整型,字符串 // 参数详解:id - 离线计分板的id,objname - 计分板登记的名称 // 返回值:若ID存在便返回具体值,若不存在则一律返回0 // (注:特定情况下会自动创建计分板) int getscoreById(__int64 id, const char* objname) { if (!scoreboard) return 0; auto testobj = scoreboard->getObjective(objname); if (!testobj) { std::cout << u8"[CSR] 未能找到对应计分板,自动创建:" << objname << std::endl; testobj = scoreboard->addObjective(objname, objname); return 0; } __int64 a2[2]{0}; __int64 sid[2]{0}; sid[0] = id; if (findScoreboardId(id, sid)) { auto scores = ((Objective*)testobj)->getplayerscoreinfo((ScoreInfo*)a2, (PlayerScoreboardId*)&sid); return scores->getcount(); } return 0; } // 函数名:setscoreById // 功能:设置指定id对应于计分板上的数值 // 参数个数:3个 // 参数类型:长整型,字符串,数值 // 参数详解:id - 离线计分板的id,objname - 计分板登记的名称,count - 待设置的值 // 返回值:若设置成功则为新数值,未成功则一律返回0 // (注:特定情况下会自动创建计分板) int setscoreById(__int64 id, const char* objname, int count) { if (!scoreboard) return 0; __int64 sid[2]{0}; sid[0] = id; auto testobj = scoreboard->getObjective(objname); if (!testobj) { std::cout << u8"[CSR] 未能找到对应计分板,自动创建: " << objname << std::endl; testobj = scoreboard->addObjective(objname, objname); } if (!testobj) return 0; if (!findScoreboardId(id, sid)) { auto v22 = GetModuleHandleW(0) + 4689324; ((void(*)(VA, VA, std::string))v22)((VA)scoreboard, (VA)sid, std::to_string(id)); } return scoreboard->modifyPlayerScore((ScoreboardId*)sid, (Objective*)testobj, count); } // 附加玩家信息 static void addPlayerInfo(PlayerEvent* pe, Player* p) { autoByteCpy(&pe->playername, p->getNameTag().c_str()); pe->dimensionid = p->getDimensionId(); autoByteCpy(&pe->dimension, toDimenStr(pe->dimensionid).c_str()); memcpy(&pe->XYZ, p->getPos(), sizeof(Vec3)); pe->isstand = p->isStand(); } static void addPlayerDieInfo(MobDieEvent* ue, Player* pPlayer) { autoByteCpy(&ue->playername, pPlayer->getNameTag().c_str()); ue->dimensionid = pPlayer->getDimensionId(); autoByteCpy(&ue->dimension, toDimenStr(ue->dimensionid).c_str()); memcpy(&ue->XYZ, pPlayer->getPos(), sizeof(Vec3)); ue->isstand = pPlayer->isStand(); } static void addMobDieInfo(MobDieEvent* ue, Mob* p) { autoByteCpy(&ue->mobname, p->getNameTag().c_str()); int did = p->getDimensionId(); ue->dimensionid = did; memcpy(&ue->XYZ, p->getPos(), sizeof(Vec3)); } // 回传伤害源信息 static void getDamageInfo(void* p, void* dsrc, MobDieEvent* ue) { // IDA Mob::die char v72; VA v2[2]; v2[0] = (VA)p; v2[1] = (VA)dsrc; auto v7 = ((Mob*)p)->getLevel(); auto srActid = (VA*)(*(VA(__fastcall**)(VA, char*))(*(VA*)v2[1] + 64))( v2[1], &v72); auto SrAct = SYMCALL(Actor*, MSSYM_B1QE11fetchEntityB1AA5LevelB2AAE13QEBAPEAVActorB2AAE14UActorUniqueIDB3AAUA1NB1AA1Z, v7, *srActid, 0); std::string sr_name = ""; std::string sr_type = ""; if (SrAct) { sr_name = SrAct->getNameTag(); int srtype = checkIsPlayer(SrAct) ? 319 : SrAct->getEntityTypeId(); SYMCALL(std::string&, MSSYM_MD5_af48b8a1869a49a3fb9a4c12f48d5a68, &sr_type, srtype); } Json::Value jv; if (checkIsPlayer(p)) { addPlayerDieInfo(ue, (Player*)p); std::string playertype; // IDA Player::getEntityTypeId SYMCALL(std::string&, MSSYM_MD5_af48b8a1869a49a3fb9a4c12f48d5a68, &playertype, 319); autoByteCpy(&ue->mobname, ue->playername); autoByteCpy(&ue->mobtype, playertype.c_str()); // "entity.player.name" } else { addMobDieInfo(ue, (Mob*)p); autoByteCpy(&ue->mobtype, ((Mob*)p)->getEntityTypeName().c_str()); } autoByteCpy(&ue->srcname, sr_name.c_str()); autoByteCpy(&ue->srctype, sr_type.c_str()); ue->dmcase = *((int*)dsrc + 2); } //////////////////////////////// 组件 API 区域 //////////////////////////////// #pragma region 类属性相关方法及实现 std::string Actor::sgetArmorContainer(Actor* e) { VA parmor = ((Mob*)e)->getArmor(); std::vector<ItemStack*> armors; (*(void(**)(VA, VA))(**(VA**)parmor + 152))(*(VA*)parmor, (VA)&armors); // IDA Mob::addAdditionalSaveData Json::Value jv; if (armors.size() > 0) { for (size_t i = 0, l = armors.size(); i < l; i++) { auto pa = armors[i]; Json::Value ji; ji["Slot"] = i; ji["item"] = pa->getName(); ji["id"] = pa->getId(); ji["rawnameid"] = pa->getRawNameId(); ji["count"] = pa->mCount; jv.append(ji); } return jv.toStyledString(); } return ""; } std::string Actor::sgetAttack(Actor* e) { if (*(VA*)(((VA*)e)[32] + 696)) { // IDA ScriptAttackComponent::retrieveComponentFrom VA atattr = (*(VA(__fastcall**)(Actor*, VA*))(*(VA*)e + 1552))( e, SYM_POINT(VA, MSSYM_B1QA6ATTACKB1UA6DAMAGEB1AE16SharedAttributesB2AAE112VAttributeB2AAA1B)); if (*(VA*)(atattr + 16)) { float dmin = *(float*)(atattr + 124); float dmax = *(float*)(atattr + 128); Json::Value jv; jv["range_min"] = dmin; jv["range_max"] = dmax; return jv.toStyledString(); } } return ""; } bool Actor::ssetAttack(Actor* e, const char* damage) { std::string dmg = damage; Json::Value jv = toJson(damage); if (!jv.isNull()) { float dmin = jv["range_min"].asFloat(); float dmax = jv["range_max"].asFloat(); VA mptr = ((VA*)e)[140]; // IDA ScriptAttackComponent::applyComponentTo if (mptr) { VA v20 = SYMCALL(VA, MSSYM_B1QE17registerAttributeB1AE16BaseAttributeMapB2AAE25QEAAAEAVAttributeInstanceB2AAE13AEBVAttributeB3AAAA1Z, mptr, SYM_POINT(VA, MSSYM_B1QA6ATTACKB1UA6DAMAGEB1AE16SharedAttributesB2AAE112VAttributeB2AAA1B)); SYMCALL(VA, MSSYM_B1QA8setRangeB1AE17AttributeInstanceB2AAA8QEAAXMMMB1AA1Z, v20, dmin, dmin, dmax); VA v22 = SYMCALL(VA, MSSYM_B1QE17registerAttributeB1AE16BaseAttributeMapB2AAE25QEAAAEAVAttributeInstanceB2AAE13AEBVAttributeB3AAAA1Z, mptr, SYM_POINT(VA, MSSYM_B1QA6ATTACKB1UA6DAMAGEB1AE16SharedAttributesB2AAE112VAttributeB2AAA1B)); SYMCALL(VA, MSSYM_B1QE19resetToDefaultValueB1AE17AttributeInstanceB2AAA7QEAAXXZ, v22); return true; } } return false; } std::string Actor::sgetCollisionBox(Actor* e) { float w = *((float*)e + 295); // IDA Actor::_refreshAABB float h = *((float*)e + 296); Json::Value jv; jv["width"] = w; jv["height"] = h; return jv.toStyledString(); } bool Actor::ssetCollisionBox(Actor* e, const char* box) { std::string sbox = box; Json::Value jv = toJson(sbox); if (!jv.isNull()) { float w = jv["width"].asFloat(); float h = jv["height"].asFloat(); if (w != 0 && h != 0) { // IDA SynchedActorData::set<float> *((float*)e + 295) = w; *((float*)e + 296) = h; SYMCALL(VA, MSSYM_B1QA7setSizeB1AA5ActorB2AAA7UEAAXMMB1AA1Z, e, w, h); SYMCALL(VA, MSSYM_B3QQDA3setB1AA1MB1AE16SynchedActorDataB2AAE10QEAAXGAEBMB1AA1Z, (VA)e + 352, ActorDataIDs::WIDTH, &w); SYMCALL(VA, MSSYM_B3QQDA3setB1AA1MB1AE16SynchedActorDataB2AAE10QEAAXGAEBMB1AA1Z, (VA)e + 352, ActorDataIDs::HEIGHT, &h); return true; } } return false; } std::string Actor::sgetHandContainer(Actor* e) { VA phand = ((Mob*)e)->getHands(); if (phand) { Json::Value jv; std::vector<ItemStack*> hands; // IDA ScriptHandContainerComponent::retrieveComponentFrom (ItemStack*)(*(VA(__fastcall**)(VA, VA))(**(VA**)phand + 152))( *(VA*)phand, (VA)&hands); if (Actor::sgetEntityTypeId(e) == 319) { ItemStack* v6 = (*(ItemStack *(__fastcall**)(Actor*))(*(VA*)e + 1216))(e); hands[0] = v6; } for (VA i = 0, l = hands.size(); i < l; i++) { ItemStack* h = hands[i]; Json::Value ji; ji["Slot"] = i; ji["item"] = h->getName(); ji["id"] = h->getId(); ji["rawnameid"] = h->getRawNameId(); ji["count"] = h->mCount; jv.append(ji); } return jv.toStyledString(); } return ""; } std::string Actor::sgetHealth(Actor* e) { VA bpattrmap = ((VA*)e)[140]; // IDA ScriptHealthComponent::retrieveComponentFrom if (bpattrmap) { VA hattr = SYMCALL(VA, MSSYM_B1QE18getMutableInstanceB1AE16BaseAttributeMapB2AAE25QEAAPEAVAttributeInstanceB2AAA1IB1AA1Z, bpattrmap, SYM_OBJECT(UINT32, MSSYM_B1QA6HEALTHB1AE16SharedAttributesB2AAE112VAttributeB2AAA1B + 4)); if (hattr) { float value = *((float*)hattr + 33); float max = *((float*)hattr + 32); Json::Value jv; jv["value"] = value; jv["max"] = max; return jv.toStyledString(); } } return ""; } bool Actor::ssetHealth(Actor* e, const char* hel) { std::string shel = hel; Json::Value jv = toJson(shel); if (!jv.isNull()) { float value = jv["value"].asFloat(); float max = jv["max"].asFloat(); VA bpattrmap = ((VA*)e)[140]; if (bpattrmap) { VA hattr = SYMCALL(VA, MSSYM_B1QE18getMutableInstanceB1AE16BaseAttributeMapB2AAE25QEAAPEAVAttributeInstanceB2AAA1IB1AA1Z, bpattrmap, SYM_OBJECT(UINT32, MSSYM_B1QA6HEALTHB1AE16SharedAttributesB2AAE112VAttributeB2AAA1B + 4)); if (hattr) { *((float*)hattr + 33) = value; *((float*)hattr + 32) = max; SYMCALL(VA, MSSYM_B2QUA8setDirtyB1AE17AttributeInstanceB2AAA7AEAAXXZ, hattr); return true; } } } return false; } std::string Actor::sgetInventoryContainer(Actor* e) { std::vector<ItemStack*> bag; // IDA ScriptInventoryContainerComponent::retrieveComponentFrom if (Actor::sgetEntityTypeId(e) == 319) { // 玩家 VA cont = ((Player*)e)->getSupplies(); (*(void(__fastcall**)(VA, void*))(*(VA*)cont + 152))( cont, &bag); } else { VA v8 = SYMCALL(VA, MSSYM_B3QQDE15tryGetComponentB1AE19VContainerComponentB3AAAA5ActorB2AAE26QEAAPEAVContainerComponentB2AAA2XZ, e); if (v8) { (*(void(__fastcall**)(VA, void*))(**(VA**)(v8 + 8) + 152))(*(VA*)(v8 + 8), &bag); } } size_t l = bag.size(); if (l > 0) { Json::Value jv; for (size_t i = 0; i < l; i++) { ItemStack* h = bag[i]; Json::Value ji; ji["Slot"] = i; ji["item"] = h->getName(); ji["id"] = h->getId(); ji["rawnameid"] = h->getRawNameId(); ji["count"] = h->mCount; jv.append(ji); } return jv.toStyledString(); } return ""; } std::string Actor::sgetName(Actor* e) { return e->getNameTag(); } bool Actor::ssetName(Actor* e, const char* n, bool alwaysShow) { std::string nname = GBKToUTF8(n); if (Actor::sgetEntityTypeId(e) == 319) { ((Player*)e)->reName(nname); } else SYMCALL(VA, MSSYM_MD5_2f9772d3549cbbfca05bc883e3dd5c30, e, nname); bool v = alwaysShow; // IDA SynchedActorData::set<signed char> SYMCALL(VA, MSSYM_B3QQDA3setB1AA1CB1AE16SynchedActorDataB2AAE10QEAAXGAEBCB1AA1Z, (VA)e + 352, ActorDataIDs::NAMETAG_ALWAYS_SHOW, &v); return true; } std::string Actor::sgetPosition(Actor* e) { auto pos = e->getPos(); Json::Value jv; if (pos) { jv["x"] = pos->x; jv["y"] = pos->y; jv["z"] = pos->z; return jv.toStyledString(); } return ""; } bool Actor::ssetPosition(Actor* e, const char* jpos) { Json::Value jv = toJson(jpos); if (!jv.isNull()) { Vec3 v; v.x = jv["x"].asFloat(); v.y = jv["y"].asFloat(); v.z = jv["z"].asFloat(); int v9 = (int)ActorType::Undefined_2; // IDA ScriptPositionComponent::applyComponentTo (*(void(__fastcall**)(Actor*, Vec3*, VA, VA, signed int, VA*))(*(VA*)e + 272))( e, &v, 1, 0, v9, SYM_POINT(VA, MSSYM_B1QA7INVALIDB1UA2IDB1AE13ActorUniqueIDB2AAA32U1B1AA1B)); if (Actor::sgetEntityTypeId(e) == 319) { v9 = (int)ActorType::Player_0; SYMCALL(VA, MSSYM_B1QE10teleportToB1AA6PlayerB2AAE13UEAAXAEBVVec3B3AAUE20NHHAEBUActorUniqueIDB3AAAA1Z, e, &v, 1, 0, v9, e->getUniqueID()); } return true; } return false; } std::string Actor::sgetRotation(Actor* e) { Json::Value jv; float x = ((float*)e)[72]; // IDA Actor::setRot float y = ((float*)e)[73]; jv["x"] = x; jv["y"] = y; return jv.toStyledString(); } bool Actor::ssetRotation(Actor* e, const char* jr) { Json::Value jv = toJson(jr); if (!jv.isNull()) { float x = jv["x"].asFloat(); float y = jv["y"].asFloat(); Vec2 v2; v2.x = x; v2.y = y; SYMCALL(VA, MSSYM_B1QA6setRotB1AA5ActorB2AAE13UEAAXAEBVVec2B3AAAA1Z, e, &v2); if (Actor::sgetEntityTypeId(e) == 319) { Vec3 c3; memcpy(&c3, e->getPos(), sizeof(Vec3)); float h = *((float*)e + 296); // IDA Actor::_refreshAABB c3.y -= (float)(1.7999999523162842 * 0.9); auto v9 = (int)ActorType::Player_0; SYMCALL(VA, MSSYM_B1QE10teleportToB1AA6PlayerB2AAE13UEAAXAEBVVec3B3AAUE20NHHAEBUActorUniqueIDB3AAAA1Z, e, &c3, 1, 0, v9, e->getUniqueID()); } return true; } return false; } int Actor::sgetDimensionId(Actor* e) { return e->getDimensionId(); } int Actor::sgetEntityTypeId(Actor* e) { return (*(int(__fastcall**)(Actor*))(*(VA*)e + 1288))(e); // IDA ScriptPositionComponent::applyComponentTo } VA Actor::sgetUniqueID(Actor* e) { return *e->getUniqueID(); } bool Actor::sremove(Actor* e) { (*(void(**)(Actor*))(*(VA*)e + 88))(e); // IDA Actor::remove , check vtable return *((char*)e + 945) == 1; } bool Actor::shurt(Actor* e, Actor* se, ActorDamageCause c, int count, bool knock, bool ignite) { ActorDamageByActorSource dmg; if (se != NULL) { SYMCALL(VA, MSSYM_B2QQE250ActorDamageByActorSourceB2AAA4QEAAB1AA9AEAVActorB2AAE18W4ActorDamageCauseB3AAAA1Z, &dmg, se, c); } else { ((VA*)&dmg)[0] = (VA)SYM_POINT(VA, MSSYM_B3QQUE187ActorDamageSourceB2AAA26BB1A); ((VA*)&dmg)[1] = (VA)c; } auto _hurt = *(bool(**)(Actor*, void*, int, bool, bool))(*(VA*)e + 0x798); // IDA Actor::_hurt, check vtable return _hurt(e, &dmg, count, knock, ignite); } Actor* Actor::sgetfromUniqueID(VA id) { if (p_level) return SYMCALL(Actor*, MSSYM_B1QE11fetchEntityB1AA5LevelB2AAE13QEBAPEAVActorB2AAE14UActorUniqueIDB3AAUA1NB1AA1Z, p_level, id, 0); return NULL; } std::vector<VA*>* Actor::sgetEntities(int did, float x1, float y1, float z1, float x2, float y2, float z2) { if (p_level) { if (did > -1 && did < 3) { AABB rt; rt.set(x1, y1, z1, x2, y2, z2); BlockSource* bs = (BlockSource*)((Level*)p_level)->getDimension(did)->getBlockSource(); return bs->getEntities((VA*)&rt); } } return NULL; } // Player相关 std::string Player::sgetHotbarContainer(Player* p) { VA cont = p->getSupplies(); if (cont) { std::vector<ItemStack*> its; // IDA ScriptHotbarContainerComponent::retrieveComponentFrom (*(void(__fastcall**)(VA, void*))(*(VA*)cont + 152))( cont, &its); if (its.size() >= 9) { Json::Value jv; for (int i = 0; i < 9; i++) { ItemStack* h = its[i]; Json::Value ji; ji["Slot"] = i; ji["item"] = h->getName(); ji["id"] = h->getId(); ji["rawnameid"] = h->getRawNameId(); ji["count"] = h->mCount; jv.append(ji); } return jv.toStyledString(); } } return ""; } std::string Player::sgetUuid(Player* p) { return p->getUuid()->toString(); } std::string Player::sgetIPPort(Player* p) { char v11[256]{0}; char v12[256]{0}; VA v4 = *(VA*)(*(VA*)(*(VA*)(p_ServerNetworkHandle + 64) + 32) + 440); auto v5 = GetModuleHandleW(0); ((void(*)(VA))(v5 + 1433268))((VA)v11); ((void(*)(VA, VA, VA))(v5 + 1440164))(v4, (VA)v11, (VA)p + 2512); ((void(*)(VA, bool, VA))(v5 + 1433184))((VA)v11, 1, (VA)v12); return std::string(v12); } void Player::saddLevel(Player* p, int lv) { SYMCALL(void, MSSYM_B1QA9addLevelsB1AA6PlayerB2AAA6UEAAXHB1AA1Z, p, lv); } __int64 Player::sgetScoreboardId(Player* p) { if (scoreboard) { auto idptr = scoreboard->getScoreboardID(p); return *(__int64*)idptr; } return -1; } __int64 Player::screateScoreboardId(Player* p) { if (scoreboard) { auto idptr = scoreboard->createPlayerScoreboardId(p); return *(__int64*)idptr; } return -1; } std::vector<VA*>* Player::sgetPlayers(int did, float x1, float y1, float z1, float x2, float y2, float z2) { if (p_level) { if (did > -1 && did < 3) { AABB rt; rt.set(x1, y1, z1, x2, y2, z2); BlockSource* bs = (BlockSource*)((Level*)p_level)->getDimension(did)->getBlockSource(); return bs->getPlayers((VA*)&rt); } } return NULL; } // 类属性相关方法 struct McMethods { std::unordered_map<std::string, void*> mcMethods; public: // 初始化,装入所有类成员属性 McMethods() { MCMETHOD m; mcMethods[m.ENTITY_GET_ARMOR_CONTAINER] = &Actor::sgetArmorContainer; mcMethods[m.ENTITY_GET_ATTACK] = &Actor::sgetAttack; mcMethods[m.ENTITY_SET_ATTACK] = &Actor::ssetAttack; mcMethods[m.ENTITY_GET_COLLISION_BOX] = &Actor::sgetCollisionBox; mcMethods[m.ENTITY_SET_COLLISION_BOX] = &Actor::ssetCollisionBox; mcMethods[m.ENTITY_GET_HAND_CONTAINER] = &Actor::sgetHandContainer; mcMethods[m.ENTITY_GET_HEALTH] = &Actor::sgetHealth; mcMethods[m.ENTITY_SET_HEALTH] = &Actor::ssetHealth; mcMethods[m.ENTITY_GET_INVENTORY_CONTAINER] = &Actor::sgetInventoryContainer; mcMethods[m.ENTITY_GET_NAME] = &Actor::sgetName; mcMethods[m.ENTITY_SET_NAME] = &Actor::ssetName; mcMethods[m.ENTITY_GET_POSITION] = &Actor::sgetPosition; mcMethods[m.ENTITY_SET_POSITION] = &Actor::ssetPosition; mcMethods[m.ENTITY_GET_ROTATION] = &Actor::sgetRotation; mcMethods[m.ENTITY_SET_ROTATION] = &Actor::ssetRotation; mcMethods[m.ENTITY_GET_DIMENSIONID] = &Actor::sgetDimensionId; mcMethods[m.ENTITY_GET_TYPEID] = &Actor::sgetEntityTypeId; mcMethods[m.ENTITY_GET_UNIQUEID] = &Actor::sgetUniqueID; mcMethods[m.ENTITY_REMOVE] = &Actor::sremove; mcMethods[m.ENTITY_HURT] = &Actor::shurt; mcMethods[m.LEVEL_GETFROM_UNIQUEID] = &Actor::sgetfromUniqueID; mcMethods[m.LEVEL_GETSFROM_AABB] = &Actor::sgetEntities; mcMethods[m.LEVEL_GETPLFROM_AABB] = &Player::sgetPlayers; mcMethods[m.PLAYER_GET_HOTBAR_CONTAINER] = &Player::sgetHotbarContainer; mcMethods[m.PLAYER_GET_UUID] = &Player::sgetUuid; mcMethods[m.PLAYER_GET_IPPORT] = &Player::sgetIPPort; mcMethods[m.PLAYER_ADD_LEVEL] = &Player::saddLevel; mcMethods[m.PLAYER_GET_SCOREID] = &Player::sgetScoreboardId; mcMethods[m.PLAYER_CREATE_SCOREID] = &Player::screateScoreboardId; } void* getMcMethod(std::string methodname) { return mcMethods[methodname]; } }; static std::unique_ptr<McMethods> _McMethods = nullptr; #pragma endregion void* mcComponentAPI(const char* method) { if (_McMethods == nullptr) _McMethods = std::make_unique<McMethods>(); return _McMethods == nullptr ? NULL : _McMethods->getMcMethod(std::string(method)); } //////////////////////////////// 静态 HOOK 区域 //////////////////////////////// #if 0 // 测试用途 int s = 5; // 强制报错 static void herror() { PR(1 / (s - 5)); } bool hooked = false; #endif // 此处开始接收异步数据 // IDA main THook2(_CS_MAIN, VA, MSSYM_A4main, VA a1, VA a2, VA a3) { initMods(); return original(a1, a2, a3); } // 获取指令队列 THook2(_CS_GETSPSCQUEUE, VA, MSSYM_MD5_3b8fb7204bf8294ee636ba7272eec000, VA _this) { p_spscqueue = original(_this); return p_spscqueue; } // 获取游戏初始化时基本信息 THook2(_CS_ONGAMESESSION, VA, MSSYM_MD5_9f3b3524a8d04242c33d9c188831f836, void* a1, void* a2, VA* a3, void* a4, void* a5, void* a6, void* a7) { p_ServerNetworkHandle = *a3; return original(a1, a2, a3, a4, a5, a6, a7); } // 获取地图初始化信息 THook2(_CS_LEVELINIT, VA, MSSYM_MD5_96d831b409d1a1984d6ac116f2bd4a55, VA a1, VA a2, VA a3, VA a4, VA a5, VA a6, VA a7, VA a8, VA a9, VA a10, VA a11, VA a12, VA a13) { VA level = original(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13); p_level = level; return level; } // 注册指令描述引用自list命令注册 THook2(_CS_ONLISTCMDREG, VA, MSSYM_B1QA5setupB1AE11ListCommandB2AAE22SAXAEAVCommandRegistryB3AAAA1Z, VA handle) { regHandle = handle; for (auto& v : cmddescripts) { std::string c = std::string(v.first); std::string ct = v.second->description; char level = v.second->level; char f1 = v.second->flag1; char f2 = v.second->flag2; SYMCALL(VA, MSSYM_MD5_8574de98358ff66b5a913417f44dd706, handle, &c, ct.c_str(), level, f1, f2); } return original(handle); } // 脚本引擎登记 THook2(_CS_ONSCRIPTENGINEINIT, bool, MSSYM_B1QE10initializeB1AE12ScriptEngineB2AAA4UEAAB1UA3NXZ, VA jse) { bool r = original(jse); if (r) { p_jsen = jse; } return r; } // 服务器后台输入指令 static bool _CS_ONSERVERCMD(VA _this, std::string* cmd) { Events e; e.type = EventType::onServerCmd; e.mode = ActMode::BEFORE; e.result = 0; ServerCmdEvent se; autoByteCpy(&se.cmd, cmd->c_str()); e.data = &se; bool ret = runCscode(ActEvent.ONSERVERCMD, ActMode::BEFORE, e); if (ret) { auto original = (bool(*)(VA, std::string*)) * getOriginalData(_CS_ONSERVERCMD); ret = original(_this, cmd); e.result = ret; e.mode = ActMode::AFTER; runCscode(ActEvent.ONSERVERCMD, ActMode::AFTER, e); } se.releaseAll(); return ret; } static VA ONSERVERCMD_SYMS[] = {1, MSSYM_MD5_b5c9e566146b3136e6fb37f0c080d91e, (VA)_CS_ONSERVERCMD }; // 服务器后台指令输出 static VA _CS_ONSERVERCMDOUTPUT(VA handle, char* str, VA size) { auto original = (VA(*)(VA, char*, VA)) * getOriginalData(_CS_ONSERVERCMDOUTPUT); if (handle == STD_COUT_HANDLE) { Events e; e.type = EventType::onServerCmdOutput; e.mode = ActMode::BEFORE; e.result = 0; ServerCmdOutputEvent soe; autoByteCpy(&soe.output, str); e.data = &soe; bool ret = runCscode(ActEvent.ONSERVERCMDOUTPUT, ActMode::BEFORE, e); if (ret) { VA result = original(handle, str, size); e.result = ret; e.mode = ActMode::AFTER; runCscode(ActEvent.ONSERVERCMDOUTPUT, ActMode::AFTER, e); soe.releaseAll(); return result; } soe.releaseAll(); return handle; } return original(handle, str, size); } static VA ONSERVERCMDOUTPUT_SYMS[] = {1, MSSYM_MD5_b5f2f0a753fc527db19ac8199ae8f740, (VA)_CS_ONSERVERCMDOUTPUT}; // 玩家选择表单 static void _CS_ONFORMSELECT(VA _this, VA id, VA handle, ModalFormResponsePacket** fp) { auto original = (void(*)(VA, VA, VA, ModalFormResponsePacket**)) * getOriginalData(_CS_ONFORMSELECT); ModalFormResponsePacket* fmp = *fp; Player* p = SYMCALL(Player*, MSSYM_B2QUE15getServerPlayerB1AE20ServerNetworkHandlerB2AAE20AEAAPEAVServerPlayerB2AAE21AEBVNetworkIdentifierB2AAA1EB1AA1Z, handle, id, *(char*)((VA)fmp + 16)); if (p != NULL) { UINT fid = fmp->getFormId(); if (releaseForm(fid)) { Events e; e.type = EventType::onFormSelect; e.mode = ActMode::BEFORE; e.result = 0; FormSelectEvent fse; addPlayerInfo(&fse, p); fse.pplayer = p; autoByteCpy(&fse.uuid, p->getUuid()->toString().c_str()); autoByteCpy(&fse.selected, fmp->getSelectStr().c_str()); // 特别鸣谢:sysca11 fse.formid = fid; e.data = &fse; bool ret = runCscode(ActEvent.ONFORMSELECT, ActMode::BEFORE, e); if (ret) { original(_this, id, handle, fp); e.result = ret; e.mode = ActMode::AFTER; runCscode(ActEvent.ONFORMSELECT, ActMode::AFTER, e); } fse.releaseAll(); return; } } original(_this, id, handle, fp); } static VA ONFORMSELECT_SYMS[] = {1, MSSYM_MD5_8b7f7560f9f8353e6e9b16449ca999d2, (VA)_CS_ONFORMSELECT}; // 玩家操作物品 static bool _CS_ONUSEITEM(void* _this, ItemStack* item, BlockPos* pBlkpos, unsigned __int8 a4, void* v5, Block* pBlk) { auto pPlayer = *reinterpret_cast<Player**>(reinterpret_cast<VA>(_this) + 8); Events e; e.type = EventType::onUseItem; e.mode = ActMode::BEFORE; e.result = 0; UseItemEvent ue; addPlayerInfo(&ue, pPlayer); ue.pplayer = pPlayer; memcpy(&ue.position, pBlkpos->getPosition(), sizeof(BPos3)); autoByteCpy(&ue.itemname, item->getName().c_str()); ue.itemid = item->getId(); ue.itemaux = item->getAuxValue(); if (pBlk) { autoByteCpy(&ue.blockname, pBlk->getLegacyBlock()->getFullName().c_str()); ue.blockid = pBlk->getLegacyBlock()->getBlockItemID(); } e.data = &ue; bool ret = runCscode(ActEvent.ONUSEITEM, ActMode::BEFORE, e); if (ret) { auto original = (bool(*)(void*, ItemStack*, BlockPos*, unsigned __int8, void*, Block*)) * getOriginalData(_CS_ONUSEITEM); ret = original(_this, item, pBlkpos, a4, v5, pBlk); e.result = ret; e.mode = ActMode::AFTER; runCscode(ActEvent.ONUSEITEM, ActMode::AFTER, e); } ue.releaseAll(); return ret; } static VA ONUSEITEM_SYMS[] = {1, MSSYM_B1QA9useItemOnB1AA8GameModeB2AAA4UEAAB1UE14NAEAVItemStackB2AAE12AEBVBlockPosB2AAA9EAEBVVec3B2AAA9PEBVBlockB3AAAA1Z, (VA)_CS_ONUSEITEM}; // 玩家放置方块 static bool _CS_ONPLACEDBLOCK(BlockSource* _this, Block* pBlk, BlockPos* pBlkpos, unsigned __int8 a4, struct Actor* pPlayer, bool _bool) { auto original = (bool(*)(BlockSource*, Block*, BlockPos*, unsigned __int8, Actor*, bool)) * getOriginalData(_CS_ONPLACEDBLOCK); if (pPlayer && checkIsPlayer(pPlayer)) { Player* pp = (Player*)pPlayer; Events e; e.type = EventType::onPlacedBlock; e.mode = ActMode::BEFORE; e.result = 0; PlacedBlockEvent pe; addPlayerInfo(&pe, pp); pe.pplayer = pp; pe.blockid = pBlk->getLegacyBlock()->getBlockItemID(); autoByteCpy(&pe.blockname, pBlk->getLegacyBlock()->getFullName().c_str()); memcpy(&pe.position, pBlkpos->getPosition(), sizeof(BPos3)); e.data = &pe; bool ret = runCscode(ActEvent.ONPLACEDBLOCK, ActMode::BEFORE, e); if (ret) { ret = original(_this, pBlk, pBlkpos, a4, pPlayer, _bool); e.result = ret; e.mode = ActMode::AFTER; runCscode(ActEvent.ONPLACEDBLOCK, ActMode::AFTER, e); } pe.releaseAll(); return ret; } return original(_this, pBlk, pBlkpos, a4, pPlayer, _bool); } static VA ONPLACEDBLOCK_SYMS[] = { 1, MSSYM_B1QA8mayPlaceB1AE11BlockSourceB2AAA4QEAAB1UE10NAEBVBlockB2AAE12AEBVBlockPosB2AAE10EPEAVActorB3AAUA1NB1AA1Z , (VA)_CS_ONPLACEDBLOCK}; // 玩家破坏方块 static bool _CS_ONDESTROYBLOCK(void* _this, BlockPos* pBlkpos) { auto pPlayer = *reinterpret_cast<Player**>(reinterpret_cast<VA>(_this) + 8); auto pBlockSource = pPlayer->getRegion(); // IDA GameMode::_destroyBlockInternal auto pBlk = pBlockSource->getBlock(pBlkpos); Events e; e.type = EventType::onDestroyBlock; e.mode = ActMode::BEFORE; e.result = 0; DestroyBlockEvent de; addPlayerInfo(&de, pPlayer); de.pplayer = pPlayer; de.blockid = pBlk->getLegacyBlock()->getBlockItemID(); autoByteCpy(&de.blockname, pBlk->getLegacyBlock()->getFullName().c_str()); memcpy(&de.position, pBlkpos->getPosition(), sizeof(BPos3)); e.data = &de; bool ret = runCscode(ActEvent.ONDESTROYBLOCK, ActMode::BEFORE, e); if (ret) { auto original = (bool(*)(void*, BlockPos*)) * getOriginalData(_CS_ONDESTROYBLOCK); ret = original(_this, pBlkpos); e.result = ret; e.mode = ActMode::AFTER; runCscode(ActEvent.ONDESTROYBLOCK, ActMode::AFTER, e); } de.releaseAll(); return ret; } static VA ONDESTROYBLOCK_SYMS[] = {1, MSSYM_B2QUE20destroyBlockInternalB1AA8GameModeB2AAA4AEAAB1UE13NAEBVBlockPosB2AAA1EB1AA1Z, (VA)_CS_ONDESTROYBLOCK}; // 玩家开箱准备 static bool _CS_ONCHESTBLOCKUSE(void* _this, Player* pPlayer, BlockPos* pBlkpos) { auto pBlockSource = (BlockSource*)((Level*)pPlayer->getLevel())->getDimension(pPlayer->getDimensionId())->getBlockSource(); auto pBlk = pBlockSource->getBlock(pBlkpos); Events e; e.type = EventType::onStartOpenChest; e.mode = ActMode::BEFORE; e.result = 0; StartOpenChestEvent de; addPlayerInfo(&de, pPlayer); de.pplayer = pPlayer; de.blockid = pBlk->getLegacyBlock()->getBlockItemID(); autoByteCpy(&de.blockname, pBlk->getLegacyBlock()->getFullName().c_str()); memcpy(&de.position, pBlkpos->getPosition(), sizeof(BPos3)); e.data = &de; bool ret = runCscode(ActEvent.ONSTARTOPENCHEST, ActMode::BEFORE, e); if (ret) { auto original = (bool(*)(void*, Player*, BlockPos*)) * getOriginalData(_CS_ONCHESTBLOCKUSE); ret = original(_this, pPlayer, pBlkpos); e.result = ret; e.mode = ActMode::AFTER; runCscode(ActEvent.ONSTARTOPENCHEST, ActMode::AFTER, e); } de.releaseAll(); return ret; } static VA ONSTARTOPENCHEST_SYMS[] = { 1, MSSYM_B1QA3useB1AE10ChestBlockB2AAA4UEBAB1UE11NAEAVPlayerB2AAE12AEBVBlockPosB2AAA1EB1AA1Z, (VA)_CS_ONCHESTBLOCKUSE }; // 玩家开桶准备 static bool _CS_ONBARRELBLOCKUSE(void* _this, Player* pPlayer, BlockPos* pBlkpos) { auto pBlockSource = (BlockSource*)((Level*)pPlayer->getLevel())->getDimension(pPlayer->getDimensionId())->getBlockSource(); auto pBlk = pBlockSource->getBlock(pBlkpos); Events e; e.type = EventType::onStartOpenBarrel; e.mode = ActMode::BEFORE; e.result = 0; StartOpenBarrelEvent de; addPlayerInfo(&de, pPlayer); de.pplayer = pPlayer; de.blockid = pBlk->getLegacyBlock()->getBlockItemID(); autoByteCpy(&de.blockname, pBlk->getLegacyBlock()->getFullName().c_str()); memcpy(&de.position, pBlkpos->getPosition(), sizeof(BPos3)); e.data = &de; bool ret = runCscode(ActEvent.ONSTARTOPENBARREL, ActMode::BEFORE, e); if (ret) { auto original = (bool(*)(void*, Player*, BlockPos*)) * getOriginalData(_CS_ONBARRELBLOCKUSE); ret = original(_this, pPlayer, pBlkpos); e.result = ret; e.mode = ActMode::AFTER; runCscode(ActEvent.ONSTARTOPENBARREL, ActMode::AFTER, e); } de.releaseAll(); return ret; } static VA ONSTARTOPENBARREL_SYMS[] = {1, MSSYM_B1QA3useB1AE11BarrelBlockB2AAA4UEBAB1UE11NAEAVPlayerB2AAE12AEBVBlockPosB2AAA1EB1AA1Z, (VA)_CS_ONBARRELBLOCKUSE}; // 玩家关闭箱子 static void _CS_ONSTOPOPENCHEST(void* _this, Player* pPlayer) { auto real_this = reinterpret_cast<void*>(reinterpret_cast<VA>(_this) - 248); auto pBlkpos = reinterpret_cast<BlockActor*>(real_this)->getPosition(); auto pBlockSource = (BlockSource*)((Level*)pPlayer->getLevel())->getDimension(pPlayer->getDimensionId())->getBlockSource(); auto pBlk = pBlockSource->getBlock(pBlkpos); Events e; e.type = EventType::onStopOpenChest; e.mode = ActMode::BEFORE; e.result = 0; StopOpenChestEvent de; addPlayerInfo(&de, pPlayer); de.pplayer = pPlayer; de.blockid = pBlk->getLegacyBlock()->getBlockItemID(); autoByteCpy(&de.blockname, pBlk->getLegacyBlock()->getFullName().c_str()); memcpy(&de.position, pBlkpos->getPosition(), sizeof(BPos3)); e.data = &de; runCscode(ActEvent.ONSTOPOPENCHEST, ActMode::BEFORE, e); auto original = (void(*)(void*, Player*)) * getOriginalData(_CS_ONSTOPOPENCHEST); original(_this, pPlayer); e.result = true; e.mode = ActMode::AFTER; runCscode(ActEvent.ONSTOPOPENCHEST, ActMode::AFTER, e); de.releaseAll(); } static VA ONSTOPOPENCHEST_SYMS[] = {1, MSSYM_B1QA8stopOpenB1AE15ChestBlockActorB2AAE15UEAAXAEAVPlayerB3AAAA1Z, (VA)_CS_ONSTOPOPENCHEST}; // 玩家关闭木桶 static void _CS_STOPOPENBARREL(void* _this, Player* pPlayer) { auto real_this = reinterpret_cast<void*>(reinterpret_cast<VA>(_this) - 248); auto pBlkpos = reinterpret_cast<BlockActor*>(real_this)->getPosition(); auto pBlockSource = (BlockSource*)((Level*)pPlayer->getLevel())->getDimension(pPlayer->getDimensionId())->getBlockSource(); auto pBlk = pBlockSource->getBlock(pBlkpos); Events e; e.type = EventType::onStopOpenBarrel; e.mode = ActMode::BEFORE; e.result = 0; StopOpenBarrelEvent de; addPlayerInfo(&de, pPlayer); de.pplayer = pPlayer; de.blockid = pBlk->getLegacyBlock()->getBlockItemID(); autoByteCpy(&de.blockname, pBlk->getLegacyBlock()->getFullName().c_str()); memcpy(&de.position, pBlkpos->getPosition(), sizeof(BPos3)); e.data = &de; runCscode(ActEvent.ONSTOPOPENBARREL, ActMode::BEFORE, e); auto original = (void(*)(void*, Player*)) * getOriginalData(_CS_STOPOPENBARREL); original(_this, pPlayer); e.result = true; e.mode = ActMode::AFTER; runCscode(ActEvent.ONSTOPOPENBARREL, ActMode::AFTER, e); de.releaseAll(); } static VA ONSTOPOPENBARREL_SYMS[] = {1, MSSYM_B1QA8stopOpenB1AE16BarrelBlockActorB2AAE15UEAAXAEAVPlayerB3AAAA1Z, (VA)_CS_STOPOPENBARREL}; // 玩家放入取出数量 static void _CS_ONSETSLOT(LevelContainerModel* a1, VA a2) { auto original = (void(*)(LevelContainerModel*, VA)) * getOriginalData(_CS_ONSETSLOT); VA* v3 = *((VA**)a1 + 26); // IDA LevelContainerModel::_getContainer BlockSource* bs = *(BlockSource**)(v3[106] + 80); BlockPos* pBlkpos = (BlockPos*)((char*)a1 + 216); Block* pBlk = bs->getBlock(pBlkpos); short id = pBlk->getLegacyBlock()->getBlockItemID(); if (id == 54 || id == 130 || id == 146 || id == -203 || id == 205 || id == 218) { // 非箱子、桶、潜影盒的情况不作处理 int slot = (int)a2; auto v5 = (*(VA(**)(LevelContainerModel*))(*(VA*)a1 + 160))(a1); if (v5) { ItemStack* pItemStack = (ItemStack*)(*(VA(**)(VA, VA))(*(VA*)v5 + 40))(v5, a2); auto nid = pItemStack->getId(); auto naux = pItemStack->getAuxValue(); auto nsize = pItemStack->getStackSize(); auto nname = std::string(pItemStack->getName()); auto pPlayer = a1->getPlayer(); Events e; e.type = EventType::onSetSlot; e.mode = ActMode::BEFORE; e.result = 0; SetSlotEvent de; addPlayerInfo(&de, pPlayer); de.pplayer = pPlayer; de.itemid = nid; de.itemcount = nsize; autoByteCpy(&de.itemname, nname.c_str()); de.itemaux = naux; memcpy(&de.position, pBlkpos, sizeof(BPos3)); de.blockid = id; autoByteCpy(&de.blockname, pBlk->getLegacyBlock()->getFullName().c_str()); de.slot = slot; e.data = &de; bool ret = runCscode(ActEvent.ONSETSLOT, ActMode::BEFORE, e); if (ret) { original(a1, a2); e.result = true; e.mode = ActMode::AFTER; runCscode(ActEvent.ONSETSLOT, ActMode::AFTER, e); } de.releaseAll(); } else original(a1, a2); } else original(a1, a2); } static VA ONSETSLOT_SYMS[] = {1, MSSYM_B1QE23containerContentChangedB1AE19LevelContainerModelB2AAA6UEAAXHB1AA1Z, (VA)_CS_ONSETSLOT}; // 玩家切换维度 static bool _CS_ONCHANGEDIMENSION(void* _this, Player* pPlayer, void* req) { Events e; e.type = EventType::onChangeDimension; e.mode = ActMode::BEFORE; e.result = 0; ChangeDimensionEvent de; addPlayerInfo(&de, pPlayer); de.pplayer = pPlayer; e.data = &de; bool ret = runCscode(ActEvent.ONCHANGEDIMENSION, ActMode::BEFORE, e); if (ret) { auto original = (bool(*)(void*, Player*, void*)) * getOriginalData(_CS_ONCHANGEDIMENSION); ret = original(_this, pPlayer, req); e.result = ret; if (ret) { // 此处刷新玩家信息 addPlayerInfo(&de, pPlayer); } e.mode = ActMode::AFTER; runCscode(ActEvent.ONCHANGEDIMENSION, ActMode::AFTER, e); } de.releaseAll(); return ret; } static VA ONCHANGEDIMENSION_SYMS[] = {1, MSSYM_B2QUE21playerChangeDimensionB1AA5LevelB2AAA4AEAAB1UE11NPEAVPlayerB2AAE26AEAVChangeDimensionRequestB3AAAA1Z , (VA)_CS_ONCHANGEDIMENSION}; // 生物死亡 static void _CS_ONMOBDIE(Mob* _this, void* dmsg) { Events e; e.type = EventType::onMobDie; e.mode = ActMode::BEFORE; e.result = 0; MobDieEvent de; getDamageInfo(_this, dmsg, &de); de.pmob = _this; e.data = &de; bool ret = runCscode(ActEvent.ONMOBDIE, ActMode::BEFORE, e); if (ret) { auto original = (void(*)(Mob*, void*))*getOriginalData(_CS_ONMOBDIE); original(_this, dmsg); e.result = ret; e.mode = ActMode::AFTER; runCscode(ActEvent.ONMOBDIE, ActMode::AFTER, e); } de.releaseAll(); } static VA ONMOBDIE_SYMS[] = { 1, MSSYM_B1QA3dieB1AA3MobB2AAE26UEAAXAEBVActorDamageSourceB3AAAA1Z, (VA)_CS_ONMOBDIE }; // 玩家重生 static void _CS_PLAYERRESPAWN(Player* pPlayer) { Events e; e.type = EventType::onRespawn; e.mode = ActMode::BEFORE; e.result = 0; RespawnEvent de; addPlayerInfo(&de, pPlayer); de.pplayer = pPlayer; e.data = &de; bool ret = runCscode(ActEvent.ONRESPAWN, ActMode::BEFORE, e); if (ret) { auto original = (void(*)(Player*)) * getOriginalData(_CS_PLAYERRESPAWN); original(pPlayer); e.result = ret; e.mode = ActMode::AFTER; addPlayerInfo(&de, pPlayer); runCscode(ActEvent.ONRESPAWN, ActMode::AFTER, e); } de.releaseAll(); } static VA ONRESPAWN_SYMS[] = { 1, MSSYM_B1QA7respawnB1AA6PlayerB2AAA7UEAAXXZ, (VA)_CS_PLAYERRESPAWN }; // 聊天消息 static void _CS_ONCHAT(void* _this, std::string& player_name, std::string& target, std::string& msg, std::string& chat_style) { Events e; e.type = EventType::onChat; e.mode = ActMode::BEFORE; e.result = 0; ChatEvent de; autoByteCpy(&de.playername, player_name.c_str()); autoByteCpy(&de.target, target.c_str()); autoByteCpy(&de.msg, msg.c_str()); autoByteCpy(&de.chatstyle, chat_style.c_str()); e.data = &de; bool ret = runCscode(ActEvent.ONCHAT, ActMode::BEFORE, e); if (ret) { auto original = (void(*)(void*, std::string&, std::string&, std::string&, std::string&)) * getOriginalData(_CS_ONCHAT); original(_this, player_name, target, msg, chat_style); e.result = ret; e.mode = ActMode::AFTER; runCscode(ActEvent.ONCHAT, ActMode::AFTER, e); } de.releaseAll(); } static VA ONCHAT_SYMS[] = {1, MSSYM_MD5_ad251f2fd8c27eb22c0c01209e8df83c, (VA)_CS_ONCHAT }; // 输入文本 static void _CS_ONINPUTTEXT(VA _this, VA id, TextPacket* tp) { Player* p = SYMCALL(Player*, MSSYM_B2QUE15getServerPlayerB1AE20ServerNetworkHandlerB2AAE20AEAAPEAVServerPlayerB2AAE21AEBVNetworkIdentifierB2AAA1EB1AA1Z, _this, id, *((char*)tp + 16)); Events e; e.type = EventType::onInputText; e.mode = ActMode::BEFORE; e.result = 0; InputTextEvent de; if (p != NULL) { addPlayerInfo(&de, p); de.pplayer = p; } autoByteCpy(&de.msg, tp->toString().c_str()); e.data = &de; bool ret = runCscode(ActEvent.ONINPUTTEXT, ActMode::BEFORE, e); if (ret) { auto original = (void(*)(VA, VA, TextPacket*)) * getOriginalData(_CS_ONINPUTTEXT); original(_this, id, tp); e.result = ret; e.mode = ActMode::AFTER; runCscode(ActEvent.ONINPUTTEXT, ActMode::AFTER, e); } de.releaseAll(); } static VA ONINPUTTEXT_SYMS[] = { 1, MSSYM_B1QA6handleB1AE20ServerNetworkHandlerB2AAE26UEAAXAEBVNetworkIdentifierB2AAE14AEBVTextPacketB3AAAA1Z, (VA)_CS_ONINPUTTEXT }; // MakeWP static Player* MakeWP(CommandOrigin& ori) { if (ori.getOriginType() == OriginType::Player) { return (Player*)ori.getEntity(); } return 0; } // 玩家执行指令 static VA _CS_ONINPUTCOMMAND(VA _this, VA mret, std::shared_ptr<CommandContext> x, char a4) { auto original = (VA(*)(VA, VA, std::shared_ptr<CommandContext>, char)) * getOriginalData(_CS_ONINPUTCOMMAND); Player* p = MakeWP(x->getOrigin()); if (p) { Events e; e.type = EventType::onInputCommand; e.mode = ActMode::BEFORE; e.result = 0; InputCommandEvent de; if (p != NULL) { addPlayerInfo(&de, p); de.pplayer = p; } autoByteCpy(&de.cmd, x->getCmd().c_str()); VA mcmd = 0; e.data = &de; bool ret = runCscode(ActEvent.ONINPUTCOMMAND, ActMode::BEFORE, e); if (ret) { mcmd = original(_this, mret, x, a4); e.result = ret; e.mode = ActMode::AFTER; runCscode(ActEvent.ONINPUTCOMMAND, ActMode::AFTER, e); } de.releaseAll(); return mcmd; } return original(_this, mret, x, a4); } static VA ONINPUTCOMMAND_SYMS[] = { 1, MSSYM_B1QE14executeCommandB1AE17MinecraftCommandsB2AAA4QEBAB1QE10AUMCRESULTB2AAA1VB2QDA6sharedB1UA3ptrB1AE15VCommandContextB3AAAA3stdB3AAUA1NB1AA1Z, (VA)_CS_ONINPUTCOMMAND }; // 玩家加载名字 THook2(_CS_ONCREATEPLAYER, VA, MSSYM_B1QE14onPlayerJoinedB1AE16ServerScoreboardB2AAE15UEAAXAEBVPlayerB3AAAA1Z, VA a1, Player* pPlayer) { VA hret = original(a1, pPlayer); Events e; e.type = EventType::onLoadName; e.mode = ActMode::BEFORE; e.result = 0; LoadNameEvent le; autoByteCpy(&le.playername, pPlayer->getNameTag().c_str()); auto uuid = pPlayer->getUuid()->toString(); autoByteCpy(&le.uuid, uuid.c_str()); autoByteCpy(&le.xuid, pPlayer->getXuid(p_level).c_str()); #if (COMMERCIAL) autoByteCpy(&le.ability, getAbilities(pPlayer).toStyledString().c_str()); #endif le.pplayer = pPlayer; e.data = &le; onlinePlayers[uuid] = pPlayer; playerSign[pPlayer] = true; bool ret = runCscode(ActEvent.ONLOADNAME, ActMode::BEFORE, e); if (ret) { e.result = ret; e.mode = ActMode::AFTER; runCscode(ActEvent.ONLOADNAME, ActMode::AFTER, e); } le.releaseAll(); return hret; } // 玩家离开游戏 THook2(_CS_ONPLAYERLEFT, void, MSSYM_B2QUE12onPlayerLeftB1AE20ServerNetworkHandlerB2AAE21AEAAXPEAVServerPlayerB3AAUA1NB1AA1Z, VA _this, Player* pPlayer, char v3) { Events e; e.type = EventType::onPlayerLeft; e.mode = ActMode::BEFORE; e.result = 0; PlayerLeftEvent le; autoByteCpy(&le.playername, pPlayer->getNameTag().c_str()); auto uuid = pPlayer->getUuid()->toString(); autoByteCpy(&le.uuid, uuid.c_str()); autoByteCpy(&le.xuid, pPlayer->getXuid(p_level).c_str()); #if (COMMERCIAL) autoByteCpy(&le.ability, getAbilities(pPlayer).toStyledString().c_str()); #endif le.pplayer = pPlayer; e.data = &le; bool ret = runCscode(ActEvent.ONPLAYERLEFT, ActMode::BEFORE, e); playerSign[pPlayer] = false; playerSign.erase(pPlayer); onlinePlayers[uuid] = NULL; onlinePlayers.erase(uuid); if (ret) { original(_this, pPlayer, v3); e.result = ret; e.mode = ActMode::AFTER; runCscode(ActEvent.ONPLAYERLEFT, ActMode::AFTER, e); } le.releaseAll(); } // 此处为防止意外崩溃出现,设置常锁 THook2(_CS_ONLOGOUT, VA, MSSYM_B3QQUE13EServerPlayerB2AAA9UEAAPEAXIB1AA1Z, Player* a1, VA a2) { mleftlock.lock(); if (playerSign[a1]) { // 非正常登出游戏用户,执行注销 playerSign[a1] = false; playerSign.erase(a1); const std::string* uuid = NULL; for (auto& p : onlinePlayers) { if (p.second == a1) { uuid = &p.first; break; } } if (uuid) onlinePlayers.erase(*uuid); } mleftlock.unlock(); return original(a1, a2); } // 玩家移动信息构筑 static VA _CS_ONMOVE(void* _this, Player* pPlayer, char v3, int v4, int v5) { auto original = (VA(*)(void*, Player*, char, int, int)) * getOriginalData(_CS_ONMOVE); VA reg = (beforecallbacks[ActEvent.ONMOVE] != NULL ? beforecallbacks[ActEvent.ONMOVE]->size() : 0) + (aftercallbacks[ActEvent.ONMOVE] != NULL ? aftercallbacks[ActEvent.ONMOVE]->size() : 0); if (!reg) return original(_this, pPlayer, v3, v4, v5); VA reto = 0; Events e; MoveEvent de; e.type = EventType::onMove; e.mode = ActMode::BEFORE; e.result = 0; addPlayerInfo(&de, pPlayer); de.pplayer = pPlayer; e.data = &de; bool ret = runCscode(ActEvent.ONMOVE, ActMode::BEFORE, e); if (ret) { reto = original(_this, pPlayer, v3, v4, v5); e.result = ret; runCscode(ActEvent.ONMOVE, ActMode::AFTER, e); } de.releaseAll(); return reto; } static VA ONMOVE_SYMS[] = {1, MSSYM_B2QQE170MovePlayerPacketB2AAA4QEAAB1AE10AEAVPlayerB2AAE14W4PositionModeB1AA11B1AA2HHB1AA1Z, (VA)_CS_ONMOVE}; // 玩家攻击监听 static bool _CS_ONATTACK(Player* pPlayer, Actor* pa) { Events e; e.type = EventType::onAttack; e.mode = ActMode::BEFORE; e.result = 0; AttackEvent de; addPlayerInfo(&de, pPlayer); de.pattacker = pPlayer; de.pattackedentity = pa; memcpy(&de.actorpos, pa->getPos(), sizeof(Vec3)); autoByteCpy(&de.actorname, pa->getNameTag().c_str()); autoByteCpy(&de.actortype, pa->getEntityTypeName().c_str()); e.data = &de; bool ret = runCscode(ActEvent.ONATTACK, ActMode::BEFORE, e); if (ret) { auto original = (bool(*)(Player*, Actor*)) * getOriginalData(_CS_ONATTACK); ret = original(pPlayer, pa); e.result = ret; e.mode = ActMode::AFTER; runCscode(ActEvent.ONATTACK, ActMode::AFTER, e); } de.releaseAll(); return ret; } static VA ONATTACK_SYMS[] = {1, MSSYM_B1QA6attackB1AA6PlayerB2AAA4UEAAB1UE10NAEAVActorB3AAAA1Z, (VA)_CS_ONATTACK}; // 全图范围爆炸监听 static void _CS_ONLEVELEXPLODE(VA _this, BlockSource* a2, Actor* a3, Vec3* a4, float a5, bool a6, bool a7, float a8, bool a9) { Events e; e.type = EventType::onLevelExplode; e.mode = ActMode::BEFORE; e.result = 0; LevelExplodeEvent de; memcpy(&de.position, a4, sizeof(Vec3)); int did = a2 ? a2->getDimensionId() : -1; de.dimensionid = did; autoByteCpy(&de.dimension, toDimenStr(did).c_str()); if (a3) { autoByteCpy(&de.entity, a3->getEntityTypeName().c_str()); de.entityid = a3->getEntityTypeId(); int i = a3->getDimensionId(); de.dimensionid = i; autoByteCpy(&de.dimension, toDimenStr(i).c_str()); } de.explodepower = a5; e.data = &de; bool ret = runCscode(ActEvent.ONLEVELEXPLODE, ActMode::BEFORE, e); if (ret) { auto original = (void(*)(VA, BlockSource*, Actor*, Vec3*, float, bool, bool, float, bool)) * getOriginalData(_CS_ONLEVELEXPLODE); original(_this, a2, a3, a4, a5, a6, a7, a8, a9); e.result = ret; e.mode = ActMode::AFTER; runCscode(ActEvent.ONLEVELEXPLODE, ActMode::AFTER, e); } de.releaseAll(); } // 重生锚爆炸监听 static bool _CS_SETRESPWNEXPLOREDE(Player* pPlayer, BlockPos* a2, BlockSource* a3, Level* a4) { // IDA auto original = (bool(*)(Player*, BlockPos*, BlockSource*, Level*)) * getOriginalData(_CS_SETRESPWNEXPLOREDE); auto v8 = a3->getBlock(a2); if (SYMCALL(int, MSSYM_B3QQDA8getStateB1AA1HB1AA5BlockB2AAE18QEBAHAEBVItemStateB3AAAA1Z, v8, SYM_POINT(VA, MSSYM_B1QE19RespawnAnchorChargeB1AE13VanillaStatesB2AAA23VB2QDE16ItemStateVariantB1AA1HB2AAA1B)) <= 0) { return original(pPlayer, a2, a3, a4); } struct VA_tmp { VA v; }; if (a3->getDimensionId() != 1) { if (!*(char*)(*((VA*)pPlayer + 107) + 7736)) { float pw = SYM_OBJECT(float, MSSYM_B2UUA4realB1AA840a00000); if (!*(char*)&(((VA_tmp*)a4)[967].v)) { if (pw != 0.0) { std::string blkname = v8->getLegacyBlock()->getFullName(); Events e; e.type = EventType::onLevelExplode; e.mode = ActMode::BEFORE; e.result = 0; LevelExplodeEvent de; de.blockid = v8->getLegacyBlock()->getBlockItemID(); autoByteCpy(&de.blockname, v8->getLegacyBlock()->getFullName().c_str()); de.dimensionid = a3->getDimensionId(); autoByteCpy(&de.dimension, toDimenStr(de.dimensionid).c_str()); de.position.x = (float)a2->getPosition()->x; de.position.y = (float)a2->getPosition()->y; de.position.z = (float)a2->getPosition()->z; de.explodepower = pw; e.data = &de; bool ret = runCscode(ActEvent.ONLEVELEXPLODE, ActMode::BEFORE, e); if (ret) { ret = original(pPlayer, a2, a3, a4); e.result = ret; e.mode = ActMode::AFTER; runCscode(ActEvent.ONLEVELEXPLODE, ActMode::AFTER, e); } de.releaseAll(); return ret; } } } } return original(pPlayer, a2, a3, a4); } static VA ONLEVELEXPLODE_SYMS[] = { 2, MSSYM_B1QA7explodeB1AA5LevelB2AAE20QEAAXAEAVBlockSourceB2AAA9PEAVActorB2AAA8AEBVVec3B2AAA1MB1UA4N3M3B1AA1Z, (VA)_CS_ONLEVELEXPLODE, MSSYM_B1QE11trySetSpawnB1AE18RespawnAnchorBlockB2AAA2CAB1UE11NAEAVPlayerB2AAE12AEBVBlockPosB2AAE15AEAVBlockSourceB2AAA9AEAVLevelB3AAAA1Z, (VA)_CS_SETRESPWNEXPLOREDE }; // 玩家切换护甲 static VA _CS_ONSETARMOR(Player* p, int slot, ItemStack* i) { auto original = (VA(*)(Player*, int, ItemStack*)) * getOriginalData(_CS_ONSETARMOR); if (checkIsPlayer(p)) { ItemStack* pItemStack = i; auto nid = pItemStack->getId(); auto naux = pItemStack->getAuxValue(); auto nsize = pItemStack->getStackSize(); auto nname = std::string(pItemStack->getName()); auto pPlayer = p; Events e; e.type = EventType::onEquippedArmor; e.mode = ActMode::BEFORE; e.result = 0; EquippedArmorEvent de; addPlayerInfo(&de, pPlayer); de.pplayer = pPlayer; de.itemid = nid; de.itemcount = nsize; autoByteCpy(&de.itemname, nname.c_str()); de.itemaux = naux; de.slot = slot; de.slottype = 0; e.data = &de; bool ret = runCscode(ActEvent.ONEQUIPPEDARMOR, ActMode::BEFORE, e); if (ret) { VA ret = original(p, slot, i); e.result = true; e.mode = ActMode::AFTER; runCscode(ActEvent.ONEQUIPPEDARMOR, ActMode::AFTER, e); return ret; } de.releaseAll(); return 0; } return original(p, slot, i); } // 玩家切换主副手 static VA _CS_ONSETCARRIEDITEM(VA v1, Player* p, ItemStack* v3, ItemStack* i, int slot) { auto original = (VA(*)(VA, Player*, ItemStack*, ItemStack*, int)) * getOriginalData(_CS_ONSETCARRIEDITEM); if (checkIsPlayer(p)) { ItemStack* pItemStack = i; auto nid = pItemStack->getId(); auto naux = pItemStack->getAuxValue(); auto nsize = pItemStack->getStackSize(); auto nname = std::string(pItemStack->getName()); auto pPlayer = p; Events e; e.type = EventType::onEquippedArmor; e.mode = ActMode::BEFORE; e.result = 0; EquippedArmorEvent de; addPlayerInfo(&de, pPlayer); de.pplayer = pPlayer; de.itemid = nid; de.itemcount = nsize; autoByteCpy(&de.itemname, nname.c_str()); de.itemaux = naux; de.slot = slot; de.slottype = 1; e.data = &de; bool ret = runCscode(ActEvent.ONEQUIPPEDARMOR, ActMode::BEFORE, e); if (ret) { VA ret = original(v1, p, v3, i, slot); e.result = true; e.mode = ActMode::AFTER; runCscode(ActEvent.ONEQUIPPEDARMOR, ActMode::AFTER, e); return ret; } de.releaseAll(); return 0; } return original(v1, p, v3, i, slot); } static VA ONSETARMOR_SYMS[] = { 2, MSSYM_B1QA8setArmorB1AE12ServerPlayerB2AAE16UEAAXW4ArmorSlotB2AAE13AEBVItemStackB3AAAA1Z, (VA)_CS_ONSETARMOR, MSSYM_B1QE27sendActorCarriedItemChangedB1AE21ActorEventCoordinatorB2AAE14QEAAXAEAVActorB2AAE16AEBVItemInstanceB2AAE111W4HandSlotB3AAAA1Z, (VA)_CS_ONSETCARRIEDITEM }; //玩家升级 static void _CS_ONLEVELUP(Player* pl, int a1) { Events e; e.type = EventType::onLevelUp; e.mode = ActMode::BEFORE; e.result = 0; LevelUpEvent le; addPlayerInfo(&le, pl); le.pplayer = pl; le.lv = a1; e.data = &le; bool ret = runCscode(ActEvent.ONLEVELUP, ActMode::BEFORE, e); if (ret) { auto original = (void(*)(Player*, int)) * getOriginalData(_CS_ONLEVELUP); original(pl, a1); e.result = ret; e.mode = ActMode::AFTER; runCscode(ActEvent.ONLEVELUP, ActMode::AFTER, e); } le.releaseAll(); } static VA ONLEVELUP_SYMS[] = { 1, MSSYM_B1QA9addLevelsB1AA6PlayerB2AAA6UEAAXHB1AA1Z, (VA)_CS_ONLEVELUP }; #if MODULE_KENGWANG // 活塞推方块事件 static bool _CS_ONPISTONPUSH(BlockActor* _this, BlockSource* a2, BlockPos* a3, UINT8 a4, UINT8 a5) { auto pBlkpos = _this->getPosition(); auto pBlockSource = a2; auto pBlk = _this->getBlock(); auto ptBlk = pBlockSource->getBlock(a3); Events e; e.type = EventType::onPistonPush; e.mode = ActMode::BEFORE; e.result = 0; PistonPushEvent de; int did = a2->getDimensionId(); de.dimensionid = did; autoByteCpy(&de.dimension, toDimenStr(did).c_str()); de.blockid = pBlk->getLegacyBlock()->getBlockItemID(); autoByteCpy(&de.blockname, pBlk->getLegacyBlock()->getFullName().c_str()); memcpy(&de.position, pBlkpos->getPosition(), sizeof(BPos3)); de.targetblockid = ptBlk->getLegacyBlock()->getBlockItemID(); autoByteCpy(&de.targetblockname, ptBlk->getLegacyBlock()->getFullName().c_str()); memcpy(&de.targetposition, a3, sizeof(BPos3)); de.direction = a5; e.data = &de; bool ret = runCscode(ActEvent.ONPISTONPUSH, ActMode::BEFORE, e); if (ret) { auto original = (bool(*)(void*, BlockSource*, BlockPos*, UINT8, UINT8)) * getOriginalData(_CS_ONPISTONPUSH); ret = original(_this, a2, a3, a4, a5); e.result = ret; e.mode = ActMode::AFTER; runCscode(ActEvent.ONPISTONPUSH, ActMode::AFTER, e); de.releaseAll(); return ret; } de.releaseAll(); return ret; } static VA ONPISTONPUSH_SYMS[] = { 1, MSSYM_B2QUE19attachedBlockWalkerB1AE16PistonBlockActorB2AAA4AEAAB1UE16NAEAVBlockSourceB2AAE12AEBVBlockPosB2AAA2EEB1AA1Z, (VA)_CS_ONPISTONPUSH }; // 箱子合并事件 static BlockSource* chestBlockSource = NULL; // 预判是否可合并 static bool _CS_ONCHESTCANPAIR(VA a1, VA a2, BlockSource* a3) { auto org = (bool(*)(VA, VA, BlockSource*)) * getOriginalData(_CS_ONCHESTCANPAIR); bool ret = org(a1, a2, a3); if (ret) { chestBlockSource = a3; } return ret; } static bool _CS_ONCHESTPAIR(BlockActor* a1, BlockActor* a2, bool a3) { auto real_this = a1; auto pBlkpos = real_this->getPosition(); auto did = chestBlockSource->getDimensionId(); auto pBlk = chestBlockSource->getBlock(pBlkpos); auto real_that = a2; auto ptBlkpos = real_that->getPosition(); auto ptBlk = chestBlockSource->getBlock(ptBlkpos);; Events e; e.type = EventType::onChestPair; e.mode = ActMode::BEFORE; e.result = 0; ChestPairEvent de; de.dimensionid = did; autoByteCpy(&de.dimension, toDimenStr(did).c_str()); de.blockid = pBlk->getLegacyBlock()->getBlockItemID(); autoByteCpy(&de.blockname, pBlk->getLegacyBlock()->getFullName().c_str()); memcpy(&de.position, pBlkpos->getPosition(), sizeof(BPos3)); de.targetblockid = ptBlk->getLegacyBlock()->getBlockItemID(); autoByteCpy(&de.targetblockname, ptBlk->getLegacyBlock()->getFullName().c_str()); memcpy(&de.targetposition, ptBlkpos->getPosition(), sizeof(BPos3)); e.data = &de; bool ret = runCscode(ActEvent.ONCHESTPAIR, ActMode::BEFORE, e); if (ret) { auto original = (bool(*)(BlockActor*, BlockActor*, bool)) * getOriginalData(_CS_ONCHESTPAIR); ret = original(a1, a2, a3); e.result = ret; e.mode = ActMode::AFTER; runCscode(ActEvent.ONCHESTPAIR, ActMode::AFTER, e); de.releaseAll(); return ret; } de.releaseAll(); return ret; } static VA ONCHESTPAIR_SYMS[] = { 2, MSSYM_B1QE11canPairWithB1AE15ChestBlockActorB2AAA4QEAAB1UE15NPEAVBlockActorB2AAE15AEAVBlockSourceB3AAAA1Z, (VA)_CS_ONCHESTCANPAIR, MSSYM_B1QA8pairWithB1AE15ChestBlockActorB2AAE10QEAAXPEAV1B2AUA1NB1AA1Z, (VA)_CS_ONCHESTPAIR }; // 生物生成检查监听 static bool _CS_ONMOBSPAWNCHECK(Mob* a1, VA a2) { auto original = (bool(*)(Mob*, VA)) * getOriginalData(_CS_ONMOBSPAWNCHECK); Events e; e.type = EventType::onMobSpawnCheck; e.mode = ActMode::BEFORE; e.result = 0; MobSpawnCheckEvent me; me.dimensionid = a1->getDimensionId(); me.pmob = a1; autoByteCpy(&me.dimension, toDimenStr(me.dimensionid).c_str()); autoByteCpy(&me.mobname, a1->getNameTag().c_str()); autoByteCpy(&me.mobtype, a1->getEntityTypeName().c_str()); memcpy(&me.XYZ, a1->getPos(), sizeof(Vec3)); e.data = &me; bool ret = runCscode(ActEvent.ONMOBSPAWNCHECK, ActMode::BEFORE, e); if (ret) { ret = original(a1, a2); e.result = ret; e.mode = ActMode::AFTER; runCscode(ActEvent.ONMOBSPAWNCHECK, ActMode::AFTER, e); me.releaseAll(); return ret; } me.releaseAll(); return ret; } static VA ONMOBSPAWNCHECK_SYMS[] = { 1, MSSYM_B1QE15checkSpawnRulesB1AA3MobB2AAA4UEAAB1UA1NB1UA1NB1AA1Z, (VA)_CS_ONMOBSPAWNCHECK }; // 玩家丢出物品 static bool _CS_ONDROPITEM(Player* pPlayer, ItemStack* itemStack, bool a3) { Events e; e.type = EventType::onDropItem; e.mode = ActMode::BEFORE; e.result = 0; PickUpItemEvent pe; addPlayerInfo(&pe, pPlayer); pe.itemid = itemStack->getId(); autoByteCpy(&pe.itemname, itemStack->getName().c_str()); pe.itemaux = itemStack->getAuxValue(); pe.pplayer = pPlayer; e.data = &pe; bool ret = runCscode(ActEvent.ONDROPITEM, ActMode::BEFORE, e); if (ret) { auto original = (bool(*)(Player*, ItemStack*, bool)) * getOriginalData(_CS_ONDROPITEM); ret = original(pPlayer, itemStack, a3); e.result = ret; e.mode = ActMode::AFTER; runCscode(ActEvent.ONDROPITEM, ActMode::AFTER, e); } pe.releaseAll(); return ret; } static VA ONDROPITEM_SYMS[] = { 1,MSSYM_B1QA4dropB1AA6PlayerB2AAA4UEAAB1UE14NAEBVItemStackB3AAUA1NB1AA1Z , (VA)_CS_ONDROPITEM }; // 玩家捡起物品 static bool _CS_ONPICKUPITEM(Player* pPlayer, ItemActor* itemactor, int a3, unsigned int a4) { ItemStack* itemStack = itemactor->getItemStack(); Events e; e.type = EventType::onPickUpItem; e.mode = ActMode::BEFORE; e.result = 0; PickUpItemEvent pe; addPlayerInfo(&pe, pPlayer); pe.itemid = itemStack->getId(); autoByteCpy(&pe.itemname, itemStack->getName().c_str()); pe.itemaux = itemStack->getAuxValue(); pe.pplayer = pPlayer; e.data = &pe; bool ret = runCscode(ActEvent.ONPICKUPITEM, ActMode::BEFORE, e); if (ret) { auto original = (bool(*)(Player*, ItemActor*, int, unsigned int)) * getOriginalData(_CS_ONPICKUPITEM); original(pPlayer, itemactor, a3, a4); e.result = ret; e.mode = ActMode::AFTER; runCscode(ActEvent.ONPICKUPITEM, ActMode::AFTER, e); } pe.releaseAll(); return ret; } static VA ONPICKUPITEM_SYMS[] = { 1, MSSYM_B1QA4takeB1AA6PlayerB2AAA4QEAAB1UE10NAEAVActorB2AAA2HHB1AA1Z, (VA)_CS_ONPICKUPITEM }; #endif #if MODULE_05007 // 计分板分数改变 static void _CS_ONSCORECHANGED(Scoreboard* class_this, ScoreboardId* a2, Objective* a3) { Events e; e.type = EventType::onScoreChanged; e.mode = ActMode::BEFORE; e.result = 0; ScoreChangedEvent pe; autoByteCpy(&pe.objectivename, a3->getscorename().c_str()); autoByteCpy(&pe.displayname, a3->getscoredisplayname().c_str()); pe.scoreboardid = a2->getId(); VA sc[2]{0}; pe.score = a3->getscoreinfo((ScoreInfo*)sc, a2)->getcount(); e.data = &pe; bool ret = runCscode(ActEvent.ONSCORECHANGED, ActMode::BEFORE, e); if (ret) { auto original = (void(*)(Scoreboard*, ScoreboardId *, Objective *)) * getOriginalData(_CS_ONSCORECHANGED); original(class_this, a2, a3); e.result = ret; e.mode = ActMode::AFTER; runCscode(ActEvent.ONSCORECHANGED, ActMode::AFTER, e); } pe.releaseAll(); } static VA ONSCORECHANGED_SYMS[] = { 1, MSSYM_B1QE14onScoreChangedB1AE16ServerScoreboardB2AAE21UEAAXAEBUScoreboardIdB2AAE13AEBVObjectiveB3AAAA1Z, (VA)_CS_ONSCORECHANGED }; #endif // 官方脚本引擎初始化 static bool _CS_ONSCRIPTENGINEINIT(VA jse) { Events e; e.type = EventType::onScriptEngineInit; e.mode = ActMode::BEFORE; e.result = 0; ScriptEngineInitEvent pe; pe.jsen = jse; e.data = &pe; bool ret = runCscode(ActEvent.ONSCRIPTENGINEINIT, ActMode::BEFORE, e); if (ret) { auto original = (bool(*)(VA)) * getOriginalData(_CS_ONSCRIPTENGINEINIT); ret = original(jse); e.result = ret; e.mode = ActMode::AFTER; runCscode(ActEvent.ONSCRIPTENGINEINIT, ActMode::AFTER, e); } return ret; } static VA ONSCRIPTENGINEINIT_SYMS[] = { 1, MSSYM_B1QE10initializeB1AE12ScriptEngineB2AAA4UEAAB1UA3NXZ, (VA)_CS_ONSCRIPTENGINEINIT }; // 官方脚本引擎输出日志信息 static bool _CS_ONSCRIPTENGINELOG(VA jse, std::string* log) { Events e; e.type = EventType::onScriptEngineLog; e.mode = ActMode::BEFORE; e.result = 0; ScriptEngineLogEvent pe; pe.jsen = jse; autoByteCpy(&pe.log, log->c_str()); e.data = &pe; bool ret = runCscode(ActEvent.ONSCRIPTENGINELOG, ActMode::BEFORE, e); if (ret) { auto original = (bool(*)(VA)) * getOriginalData(_CS_ONSCRIPTENGINELOG); ret = original(jse); e.result = ret; e.mode = ActMode::AFTER; runCscode(ActEvent.ONSCRIPTENGINELOG, ActMode::AFTER, e); } pe.releaseAll(); return ret; } static VA ONSCRIPTENGINELOG_SYMS[] = { 1, MSSYM_MD5_a46384deb7cfca46ec15102954617155 , (VA)_CS_ONSCRIPTENGINELOG }; // 官方脚本引擎执行指令 static bool _CS_ONSCRIPTENGINECMD(VA a1, VA jscmd) { std::string* cmd = (std::string*)(jscmd + 8); Events e; e.type = EventType::onScriptEngineCmd; e.mode = ActMode::BEFORE; e.result = 0; ScriptEngineCmdEvent pe; pe.jsen = p_jsen; autoByteCpy(&pe.log, cmd->c_str()); e.data = &pe; bool ret = runCscode(ActEvent.ONSCRIPTENGINECMD, ActMode::BEFORE, e); if (ret) { auto original = (bool(*)(VA, VA)) * getOriginalData(_CS_ONSCRIPTENGINECMD); ret = original(a1, jscmd); e.result = ret; e.mode = ActMode::AFTER; runCscode(ActEvent.ONSCRIPTENGINECMD, ActMode::AFTER, e); } pe.releaseAll(); return ret; } static VA ONSCRIPTENGINECMD_SYMS[] = { 1, MSSYM_B1QE14executeCommandB1AE27MinecraftServerScriptEngineB2AAA4UEAAB1UE18NAEBUScriptCommandB3AAAA1Z , (VA)_CS_ONSCRIPTENGINECMD }; // 系统计分板初始化 static VA _CS_ONSCOREBOARDINIT(VA a1, VA a2, VA a3) { Events e; e.type = EventType::onScoreboardInit; e.mode = ActMode::BEFORE; e.result = 0; ScoreboardInitEvent pe; pe.scptr = a1; e.data = &pe; bool ret = runCscode(ActEvent.ONSCOREBOARDINIT, ActMode::BEFORE, e); if (ret) { auto original = (VA(*)(VA, VA, VA)) * getOriginalData(_CS_ONSCOREBOARDINIT); VA r = original(a1, a2, a3); e.result = ret; e.mode = ActMode::AFTER; runCscode(ActEvent.ONSCOREBOARDINIT, ActMode::AFTER, e); return r; } return 0; } static VA ONSCOREBOARDINIT_SYMS[] = { 1, MSSYM_B2QQE170ServerScoreboardB2AAA4QEAAB1AE24VCommandSoftEnumRegistryB2AAE16PEAVLevelStorageB3AAAA1Z, (VA)_CS_ONSCOREBOARDINIT }; // 初始化各类hook的事件绑定,基于构造函数 static struct EventSymsInit{ public: EventSymsInit() { sListens[ActEvent.ONSERVERCMD] = ONSERVERCMD_SYMS; sListens[ActEvent.ONSERVERCMDOUTPUT] = ONSERVERCMDOUTPUT_SYMS; sListens[ActEvent.ONFORMSELECT] = ONFORMSELECT_SYMS; sListens[ActEvent.ONUSEITEM] = ONUSEITEM_SYMS; sListens[ActEvent.ONMOVE] = ONMOVE_SYMS; sListens[ActEvent.ONATTACK] = ONATTACK_SYMS; sListens[ActEvent.ONPLACEDBLOCK] = ONPLACEDBLOCK_SYMS; sListens[ActEvent.ONDESTROYBLOCK] = ONDESTROYBLOCK_SYMS; sListens[ActEvent.ONSTARTOPENCHEST] = ONSTARTOPENCHEST_SYMS; sListens[ActEvent.ONSTARTOPENBARREL] = ONSTARTOPENBARREL_SYMS; sListens[ActEvent.ONCHANGEDIMENSION] = ONCHANGEDIMENSION_SYMS; isListened[ActEvent.ONLOADNAME] = true; isListened[ActEvent.ONPLAYERLEFT] = true; sListens[ActEvent.ONSTOPOPENCHEST] = ONSTOPOPENCHEST_SYMS; sListens[ActEvent.ONSTOPOPENBARREL] = ONSTOPOPENBARREL_SYMS; sListens[ActEvent.ONSETSLOT] = ONSETSLOT_SYMS; sListens[ActEvent.ONMOBDIE] = ONMOBDIE_SYMS; sListens[ActEvent.ONRESPAWN] = ONRESPAWN_SYMS; sListens[ActEvent.ONCHAT] = ONCHAT_SYMS; sListens[ActEvent.ONINPUTTEXT] = ONINPUTTEXT_SYMS; sListens[ActEvent.ONINPUTCOMMAND] = ONINPUTCOMMAND_SYMS; sListens[ActEvent.ONLEVELEXPLODE] = ONLEVELEXPLODE_SYMS; sListens[ActEvent.ONEQUIPPEDARMOR] = ONSETARMOR_SYMS; sListens[ActEvent.ONLEVELUP] = ONLEVELUP_SYMS; #if MODULE_KENGWANG sListens[ActEvent.ONPISTONPUSH] = ONPISTONPUSH_SYMS; sListens[ActEvent.ONCHESTPAIR] = ONCHESTPAIR_SYMS; sListens[ActEvent.ONMOBSPAWNCHECK] = ONMOBSPAWNCHECK_SYMS; sListens[ActEvent.ONDROPITEM] = ONDROPITEM_SYMS; sListens[ActEvent.ONPICKUPITEM] = ONPICKUPITEM_SYMS; #endif #if MODULE_05007 sListens[ActEvent.ONSCORECHANGED] = ONSCORECHANGED_SYMS; #endif sListens[ActEvent.ONSCRIPTENGINEINIT] = ONSCRIPTENGINEINIT_SYMS; sListens[ActEvent.ONSCRIPTENGINELOG] = ONSCRIPTENGINELOG_SYMS; sListens[ActEvent.ONSCRIPTENGINECMD] = ONSCRIPTENGINECMD_SYMS; sListens[ActEvent.ONSCOREBOARDINIT] = ONSCOREBOARDINIT_SYMS; #if (COMMERCIAL) isListened[ActEvent.ONMOBHURT] = true; isListened[ActEvent.ONBLOCKCMD] = true; isListened[ActEvent.ONNPCCMD] = true; isListened[ActEvent.ONCOMMANDBLOCKUPDATE] = true; #endif } } _EventSymsInit; static char localpath[MAX_PATH] = { 0 }; // 获取BDS完整程序路径 static std::string getLocalPath() { if (!localpath[0]) { GetModuleFileNameA(NULL, localpath, _countof(localpath)); for (size_t l = strlen(localpath); l != 0; l--) { if (localpath[l] == '\\') { localpath[l] = localpath[l + 1] = localpath[l + 2] = 0; break; } } } return std::string(localpath); } static bool inited = false; static VA attcount = 0; static ICLRMetaHost* pMetaHost = nullptr; static ICLRMetaHostPolicy* pMetaHostPolicy = nullptr; static ICLRRuntimeHost* pRuntimeHost = nullptr; static ICLRRuntimeInfo* pRuntimeInfo = nullptr; // 初始化.Net环境 static void initNetFramework() { SetCurrentDirectoryA(getLocalPath().c_str()); std::string plugins = "plugins/"; std::string settingdir = plugins + "settings/"; // 固定配置文件目录 - plugins/settings std::string settingpath = settingdir + "csrsetting.ini"; // 固定配置文件 - csrsetting.ini char csrpath[MAX_PATH]{ 0 }; std::string path = ""; auto len = GetPrivateProfileStringA("CSR", "csrdir", NULL, csrpath, MAX_PATH, settingpath.c_str()); if (len < 1) { PR(u8"[CSR] 未能读取Net插件库路径配置文件,使用默认配置[详见" + settingpath + u8"]"); path = "CSR"; // 默认路径 - CSR CreateDirectoryA(plugins.c_str(), 0); CreateDirectoryA(settingdir.c_str(), 0); WritePrivateProfileStringA("CSR", "csrdir", "CSR", settingpath.c_str()); } else { path = csrpath; } // 此处判断插件库是否存在 if (!PathIsDirectoryA(path.c_str())) { PR(u8"[CSR] 未检测到csr插件文件夹 " + path + u8" 存在,请检查配置是否正确[详见" + settingpath + u8"]"); return; } std::string pair = path + "\\*.csr.dll"; std::vector<std::wstring> csrdlls; WIN32_FIND_DATAA ffd; HANDLE dfh = FindFirstFileA(pair.c_str(), &ffd); if (INVALID_HANDLE_VALUE != dfh) { do { if (!(ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { std::string fileName = std::string(path + "\\" + ffd.cFileName); std::wstring w_str = toGBKString(fileName); csrdlls.push_back(w_str); } } while (FindNextFileA(dfh, &ffd) != 0); FindClose(dfh); } if (csrdlls.size() < 1) return; // 此处开始初始化.net framework DWORD dwRet = 0; HRESULT hr = CLRCreateInstance(CLSID_CLRMetaHost, IID_ICLRMetaHost, (LPVOID*)&pMetaHost); hr = pMetaHost->GetRuntime(L"v4.0.30319", IID_PPV_ARGS(&pRuntimeInfo)); if (!FAILED(hr)) { hr = pRuntimeInfo->GetInterface(CLSID_CLRRuntimeHost, IID_PPV_ARGS(&pRuntimeHost)); if (FAILED(hr)) return; hr = pRuntimeHost->Start(); if (FAILED(hr)) return; std::wstring curDllandVer = GetDllPathandVersion(); // 获取平台路径和版本,逗号分隔 // 加载所有csr插件 for (auto& w_str : csrdlls) { LPCWSTR dllName = w_str.c_str(); std::wcout << L"[CSR] load " << dllName << std::endl; hr = pRuntimeHost->ExecuteInDefaultAppDomain(dllName, // 插件实际路径 L"CSR.Plugin", // 插件通用类名 L"onServerStart", // 插件通用初始化接口 curDllandVer.c_str(), // 回传lib和版本号 &dwRet); if (FAILED(hr)) { wprintf(L"[File] %s api load failed.\n", dllName); continue; } } } else { releaseNetFramework(); } } // 卸载.Net环境 static void releaseNetFramework() { beforecallbacks.clear(); aftercallbacks.clear(); if (pRuntimeHost != nullptr) pRuntimeHost->Stop(); if (pRuntimeInfo != nullptr) { pRuntimeInfo->Release(); pRuntimeInfo = nullptr; } if (pRuntimeHost != nullptr) { pRuntimeHost->Release(); pRuntimeHost = nullptr; } if (pMetaHost != nullptr) { pMetaHost->Release(); pMetaHost = nullptr; } } // 附加调用函数 static std::unordered_map<std::string, void*> extraApi; static void initExtraApi() { #if (COMMERCIAL) extraApi["getStructure"] = &getStructure; extraApi["setStructure"] = &setStructure; extraApi["getPlayerAbilities"] = &getPlayerAbilities; extraApi["setPlayerAbilities"] = &setPlayerAbilities; extraApi["getPlayerAttributes"] = &getPlayerAttributes; extraApi["setPlayerTempAttributes"] = &setPlayerTempAttributes; extraApi["getPlayerMaxAttributes"] = &getPlayerMaxAttributes; extraApi["setPlayerMaxAttributes"] = &setPlayerMaxAttributes; extraApi["getPlayerItems"] = &getPlayerItems; extraApi["setPlayerItems"] = &setPlayerItems; extraApi["getPlayerSelectedItem"] = &getPlayerSelectedItem; extraApi["addPlayerItemEx"] = &addPlayerItemEx; extraApi["getPlayerEffects"] = &getPlayerEffects; extraApi["setPlayerEffects"] = &setPlayerEffects; extraApi["setPlayerBossBar"] = &setPlayerBossBar; extraApi["removePlayerBossBar"] = &removePlayerBossBar; extraApi["transferserver"] = &transferserver; extraApi["teleport"] = &teleport; extraApi["setPlayerSidebar"] = &setPlayerSidebar; extraApi["removePlayerSidebar"] = &removePlayerSidebar; extraApi["getPlayerPermissionAndGametype"] = &getPlayerPermissionAndGametype; extraApi["setPlayerPermissionAndGametype"] = &setPlayerPermissionAndGametype; #endif } void* getExtraAPI(const char* apiname) { std::string k = std::string(apiname); return extraApi[k]; } // 初始化工作 static void initMods() { if (inited) { return; } inited = true; initNetFramework(); } // 底层相关 static std::unordered_map<void*, void**> hooks; // 获取指定原型存储位置 void** getOriginalData(void* hook) { return hooks[hook]; } // 挂载hook HookErrorCode mTHook2(RVA sym, void* hook) { hooks[hook] = new void* [1]{ 0 }; void** org = hooks[hook]; *org = ((char*)GetModuleHandle(NULL)) + sym; return Hook<void*>(org, hook); } unsigned long long dlsym(int rva) { return (VA)GetModuleHandle(NULL) + rva; } bool cshook(int rva, void* hook, void** org) { *org = ((char*)GetModuleHandle(NULL)) + rva; return Hook<void*>(org, hook) == HookErrorCode::ERR_SUCCESS; } bool csunhook(void* hook, void** org) { return UnHook<void*>(org, hook) == HookErrorCode::ERR_SUCCESS; } bool readHardMemory(int rva, unsigned char* odata, int size) { //修改页都保护属性 DWORD dwOldProtect1, dwOldProtect2 = PAGE_READONLY; MEMORY_BASIC_INFORMATION mbi; auto x = SYM_POINT(char, rva); SIZE_T num = 1; VirtualQuery(x, &mbi, sizeof(mbi)); VirtualProtectEx(GetCurrentProcess(), x, size, dwOldProtect2, &dwOldProtect1); ReadProcessMemory(GetCurrentProcess(), x, odata, size, &num); //恢复页都保护属性 return VirtualProtectEx(GetCurrentProcess(), x, size, dwOldProtect1, &dwOldProtect2); } bool writeHardMemory(int rva, unsigned char* ndata, int size) { //修改页都保护属性 DWORD dwOldProtect1, dwOldProtect2 = PAGE_READWRITE; MEMORY_BASIC_INFORMATION mbi; auto x = SYM_POINT(char, rva); SIZE_T num = 1; VirtualQuery(x, &mbi, sizeof(mbi)); VirtualProtectEx(GetCurrentProcess(), x, size, dwOldProtect2, &dwOldProtect1); WriteProcessMemory(GetCurrentProcess(), x, ndata, size, &num); //恢复页都保护属性 return VirtualProtectEx(GetCurrentProcess(), x, size, dwOldProtect1, &dwOldProtect2); } void init() { #if (!COMMERCIAL) std::cout << u8"{[插件] Net插件运行平台(社区版)已装载。此平台基于LGPL协议发行。" << std::endl; #else std::cout << u8"{[插件] Net插件运行平台已装载。" << std::endl; #endif std::wcout << L"version=" << VERSION << std::endl; } void exit() { releaseNetFramework(); }
94,809
C++
.cpp
2,726
30.334556
188
0.688166
zhkj-liuxiaohua/BDSNetRunner
37
8
0
LGPL-2.1
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,709
scoreboard.cpp
zhkj-liuxiaohua_BDSNetRunner/BDSNetRunner/scoreboard/scoreboard.cpp
#include "scoreboard.hpp" #include "../mod.h" #if (MODULE_05007) Scoreboard* scoreboard;//储存计分板名称 //获取玩家在指定计分板下的内容(返回整数,在这个计分板下这个玩家的值) int getscoreboard(Player* p, std::string objname) { auto testobj = scoreboard->getObjective(objname); if (!testobj) { std::cout << u8"[CSR] 未能找到对应计分板,自动创建:" << objname << std::endl; testobj = scoreboard->addObjective(objname, objname); return 0; } __int64 a2[2]; auto scoreid = scoreboard->getScoreboardID(p); auto scores = ((Objective*)testobj)->getplayerscoreinfo((ScoreInfo*)a2, scoreid); return scores->getcount(); } bool setscoreboard(Player* p, std::string objname, int count) { auto testobj = scoreboard->getObjective(objname); if (!testobj) { std::cout << u8"[CSR] 未能找到对应计分板,自动创建: " << objname << std::endl; testobj = scoreboard->addObjective(objname, objname); } if (!testobj) return false; VA scoreid = (VA)scoreboard->getScoreboardID(p); if (scoreid == (VA)SYM_POINT(VA, MSSYM_B1QA7INVALIDB1AE12ScoreboardIdB2AAA32U1B1AA1A)) { std::cout << u8"[CSR] 未能找到玩家对应计分板,自动设置: " << objname << std::endl; scoreid = scoreboard->createPlayerScoreboardId(p); } if (!scoreid || scoreid == (VA)SYM_POINT(VA, MSSYM_B1QA7INVALIDB1AE12ScoreboardIdB2AAA32U1B1AA1A)) return false; scoreboard->modifyPlayerScore((ScoreboardId*)scoreid, (Objective*)testobj, count); return true; } // 计分板命令注册(开服时获取所有的计分板名称) THook(void*, MSSYM_B2QQE170ServerScoreboardB2AAA4QEAAB1AE24VCommandSoftEnumRegistryB2AAE16PEAVLevelStorageB3AAAA1Z, void* _this, void* a2, void* a3) { scoreboard = (Scoreboard*)original(_this, a2, a3); return scoreboard; } #endif
1,758
C++
.cpp
41
37.04878
151
0.731371
zhkj-liuxiaohua/BDSNetRunner
37
8
0
LGPL-2.1
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,710
SimpleForm.cpp
zhkj-liuxiaohua_BDSNetRunner/BDSNetRunner/GUI/SimpleForm.cpp
#include <string> #include <json\json.h> std::string createSimpleFormString(std::string title, std::string content, Json::Value & bttxts) { Json::Value jv; jv["type"] = "form"; jv["title"] = title; jv["content"] = content; jv["buttons"] = bttxts; return jv.toStyledString(); } std::string createModalFormString(std::string title, std::string content, std::string button1, std::string button2) { Json::Value jv; jv["type"] = "modal"; jv["title"] = title; jv["content"] = content; jv["button1"] = button1; jv["button2"] = button2; return jv.toStyledString(); }
595
C++
.cpp
19
28.421053
118
0.676573
zhkj-liuxiaohua/BDSNetRunner
37
8
0
LGPL-2.1
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,712
BDS.hpp
zhkj-liuxiaohua_BDSNetRunner/BDSNetRunner/BDS.hpp
#pragma once #include <string> #include "THook.h" #include "RVAs.hpp" #include <json/json.h> #include "Component.h" // 方块坐标结构体 #pragma region Blocks 定义方块结构体 struct BPos3 { INT32 x; INT32 y; INT32 z; public: std::string toJsonString() { char str[256]; sprintf_s(str, "{\"x\":%d,\"y\":%d,\"z\":%d}", x, y, z); return std::string(str); } }; struct BlockLegacy { // 获取方块名 auto getFullName() const { // IDA BlockLegacy::~BlockLegacy return (std::string&) * (__int64*)((__int64)this + 120); } // 获取方块ID号 auto getBlockItemID() const { // IDA BlockLegacy::BlockLegacy VanillaItems::serverInitCreativeItemsCallback Item::beginCreativeGroup "itemGroup.name.planks" short v3 = *(short*)((VA)this + 312); if (v3 < 0x100) { return v3; } return (short)(255 - v3); } }; struct BlockPos : BPos3 { // 获取坐标数组头 BPos3* getPosition() const { return (BPos3*)this; } //通过 BDS 的指令原生输出 std::string toString() { std::string s; SYMCALL(std::string&, MSSYM_MD5_08038beb99b82fbb46756aa99d94b86f, this, &s); return s; } // 通过 Vec3 构造 BlockPos BlockPos(const void* vec3) { auto v = (float*)vec3; x = v ? (int)v[0] : 0; y = v ? (int)v[1] : 0; z = v ? (int)v[2] : 0; } // 通过 double 构造 BlockPos BlockPos(double x2, double y2, double z2) { x = (int)x2; y = (int)y2; z = (int)z2; } BlockPos() { memset(this, 0, sizeof(BlockPos)); } }; struct Block { // 获取源 const BlockLegacy* getLegacyBlock() const { // IDA LegacyStructureTemplate::_mapToProperty "waterlogged" return SYMCALL(BlockLegacy*, MSSYM_B1QE14getLegacyBlockB1AA5BlockB2AAE19QEBAAEBVBlockLegacyB2AAA2XZ, this); } }; struct BlockActor { // 取方块 Block* getBlock() { return *reinterpret_cast<Block**>(reinterpret_cast<VA>(this) + 16); } // 取方块位置 BlockPos* getPosition() { // IDA BlockActor::BlockActor return reinterpret_cast<BlockPos*>(reinterpret_cast<VA>(this) + 44); } }; struct BlockSource { // 取方块 Block* getBlock(const BlockPos* blkpos) { return SYMCALL(Block*, MSSYM_B1QA8getBlockB1AE11BlockSourceB2AAE13QEBAAEBVBlockB2AAE12AEBVBlockPosB3AAAA1Z, this, blkpos); } // 获取方块所处维度 int getDimensionId() { // IDA Dimension::onBlockChanged return *(int*)(*((VA*)this + 4) + 200); } // 获取指定范围内所有实体 std::vector<VA*>* getEntities(VA *rect) { return SYMCALL(std::vector<VA*>*, MSSYM_MD5_73d55bcf0da8c45a15024daf84014ad7, this, 0, rect, 1); } // 获取指定范围内所有玩家 std::vector<VA*>* getPlayers(VA* rect) { return SYMCALL(std::vector<VA*>*, MSSYM_MD5_73d55bcf0da8c45a15024daf84014ad7, this, ActorType::Player_0, rect, 0); } //获取方块操作器 BlockActor* getBlockActor(const BlockPos* blkpos) { return SYMCALL(BlockActor*, MSSYM_B1QE14getBlockEntityB1AE11BlockSourceB2AAE18QEAAPEAVBlockActorB2AAE12AEBVBlockPosB3AAAA1Z, this, blkpos); } }; struct Dimension { // 获取方块源 VA getBlockSource() { // IDA Level::tickEntities return *((VA*)this + 10); } }; struct Level { // 获取维度 Dimension* getDimension(int did) { return SYMCALL(Dimension*, MSSYM_B1QE12getDimensionB1AA5LevelB2AAE17QEBAPEAVDimensionB2AAA1VB2QDE11AutomaticIDB1AE10VDimensionB2AAA1HB3AAAA1Z, this, did); } }; #pragma endregion #pragma region Actors 定义实体结构体 struct MCUUID { // 取uuid字符串 std::string toString() { std::string s; SYMCALL(std::string&, MSSYM_MD5_40e8abf6eb08f7ee446159cdd0a7f283, this, &s); return s; } }; // 玩家坐标结构体 struct Vec3 { float x; float y; float z; std::string toJsonString() { char str[256]; sprintf_s(str, "{\"x\":%.2f,\"y\":%.2f,\"z\":%.2f}", x, y, z); return std::string(str); } }; // 区域范围结构体 struct AABB { Vec3 min; Vec3 max; bool empty; // 重设两点 void set(float x1, float y1, float z1, float x2, float y2, float z2) { min.x = std::min<float>(x1, x2); min.y = std::min<float>(y1, y2); min.z = std::min<float>(z1, z2); max.x = std::max<float>(x1, x2); max.y = std::max<float>(y1, y2); max.z = std::max<float>(z1, z2); empty = (min.x == 0.0 && min.y == 0.0 && min.z == 0.0 && max.x == 0.0 && max.y == 0.0 && max.z == 0.0); } // 从两点间获取一个区域 bool fromPoints(Vec3 *a, Vec3 *b) { if (!a || !b) return false; min.x = std::min<float>(a->x, b->x); min.y = std::min<float>(a->y, b->y); min.z = std::min<float>(a->z, b->z); max.x = std::max<float>(a->x, b->x); max.y = std::max<float>(a->y, b->y); max.z = std::max<float>(a->z, b->z); empty = (min.x == 0.0 && min.y == 0.0 && min.z == 0.0 && max.x == 0.0 && max.y == 0.0 && max.z == 0.0); return true; } }; // 玩家转角结构体 struct Vec2 { float x; float y; }; struct Actor { #pragma region 通用属性 // 导出API,获取穿戴信息,只读 static std::string sgetArmorContainer(Actor*); // 导出API,获取攻击力 static std::string sgetAttack(Actor*); // 导出API,设置攻击力 static bool ssetAttack(Actor*, const char*); // 导出API,获取碰撞箱 static std::string sgetCollisionBox(Actor*); // 导出API,设置碰撞箱 static bool ssetCollisionBox(Actor*, const char*); // damage_sensor,伤害指示器,复杂类型,略 // equipment,装备掉率列表,复杂类型,略 // equippable,允许装备内容列表,复杂类型,略 // explode,爆炸力,复杂类型,略 // 导出API,获取主副手装备,只读 static std::string sgetHandContainer(Actor*); // healable,补品列表,复杂类型,略 // 导出API,获取生命值 static std::string sgetHealth(Actor*); // 导出API,设置生命值 static bool ssetHealth(Actor*, const char*); // interact,玩家与实体的交互动作,复杂类型,略 // inventory,实体背包类型,复杂类型,略 // 导出API,获取实体容器列表,只读 static std::string sgetInventoryContainer(Actor*); // lookat,敌对关注,复杂类型,略 // nameable,自定义名称相关属性,复杂类型,略 // 导出API,获取名称信息 static std::string sgetName(Actor*); // 导出API,设置名称信息,是否一直显示 static bool ssetName(Actor*, const char*, bool); // 导出API,获取三维坐标信息 static std::string sgetPosition(Actor*); // 导出API,设置三维坐标 static bool ssetPosition(Actor*, const char*); // 导出API,获取实体转角信息 static std::string sgetRotation(Actor*); // 导出API,设置实体转角 static bool ssetRotation(Actor*, const char*); // shooter,定义实体发射飞行物属性,需要实体具有projectile组件,复杂类型,略 // spawn_entity,定义实体诞生其它新实体的属性(如鸡等),复杂类型,略 // teleport,定义实体自随机传送属性(如末影人等),复杂类型,略 // tick_world,实体可用更新域、于世界的刷新行为等,复杂类型,略 // 导出API,获取维度ID,只读 static int sgetDimensionId(Actor*); // 导出API,获取实体类型ID,只读 static int sgetEntityTypeId(Actor*); // 导出API,获取查询ID,只读 static VA sgetUniqueID(Actor*); // 导出API,移除该实体 static bool sremove(Actor*); // 导出API,模拟该实体产生一个源自另一实体的伤害 static bool shurt(Actor*, Actor*, ActorDamageCause, int, bool, bool); // 导出API,根据查询ID反查实体指针 static Actor* sgetfromUniqueID(VA); // 导出API,查询指定维度指定坐标范围内所有实体 static std::vector<VA*>* sgetEntities(int, float, float, float, float, float, float); #pragma endregion // 取方块源 BlockSource* getRegion() { // IDA return (BlockSource*)*((VA*)this + 105); } // 获取生物名称信息 std::string getNameTag() { return SYMCALL(std::string&, MSSYM_MD5_7044ab83168b0fd345329e6566fd47fd, this); } // 获取生物当前所处维度ID int getDimensionId() { int dimensionId; SYMCALL(int&, MSSYM_B1QE14getDimensionIdB1AA5ActorB2AAA4UEBAB1QA2AVB2QDE11AutomaticIDB1AE10VDimensionB2AAA1HB2AAA2XZ, this, &dimensionId); return dimensionId; } // 是否悬空 const BYTE isStand() { // IDA MovePlayerPacket::MovePlayerPacket return *reinterpret_cast<BYTE*>(reinterpret_cast<VA>(this) + 448); } // 获取生物当前所在坐标 Vec3* getPos() { return SYMCALL(Vec3*, MSSYM_B1QA6getPosB1AA5ActorB2AAE12UEBAAEBVVec3B2AAA2XZ, this); } #if 0 // 获取生物类型,无法获取命名生物正确类型,本函数废弃 std::string getTypeName() { std::string actor_typename; // IDA ActorCommandOrigin::getName CommandUtils::getActorName SYMCALL(std::string&, MSSYM_MD5_41a18e1578312643b066a562efefb36a, &actor_typename, this); return actor_typename; } #endif // 获取实体类型 int getEntityTypeId() { return sgetEntityTypeId(this); } // 获取查询用ID VA* getUniqueID() { return SYMCALL(VA*, MSSYM_B1QE11getUniqueIDB1AA5ActorB2AAE21QEBAAEBUActorUniqueIDB2AAA2XZ, this); } // 获取实体名称 std::string getEntityTypeName() { std::string en_name; SYMCALL(std::string&, MSSYM_MD5_af48b8a1869a49a3fb9a4c12f48d5a68, &en_name, getEntityTypeId()); return en_name; } #if 0 // TODO MODULE_KENGWANG, XXX // 骑乘 void AddRider(Actor* actor) { SYMCALL(void, MSSYM_B1QA8addRiderB1AA5ActorB2AAE10UEAAXAEAV1B2AAA1Z, this, actor); } #endif }; struct Mob : Actor { // 获取装备容器 VA getArmor() { // IDA Mob::addAdditionalSaveData return VA(this) + 1472; } // 获取手头容器 VA getHands() { return VA(this) + 1480; // IDA Mob::readAdditionalSaveData } // 获取地图信息 VA getLevel() { // IDA Mob::die return *((VA*)((VA)this + 856)); } }; struct Player : Mob { #pragma region 通用属性 // 导出API,获取热键装备列表,只读 static std::string sgetHotbarContainer(Player*); // 导出API,获取玩家uuid,只读 static std::string sgetUuid(Player*); // 导出API,获取玩家网络IP和端口,只读 static std::string sgetIPPort(Player*); // 导出API,增加玩家等级 static void saddLevel(Player*, int); // 导出API,获取玩家对应计分板ID值 static __int64 sgetScoreboardId(Player*); // 导出API,创建玩家对应计分板并获取其ID值 static __int64 screateScoreboardId(Player*); // 导出API,查询指定维度指定坐标范围内所有玩家 static std::vector<VA*>* sgetPlayers(int, float, float, float, float, float, float); #pragma endregion // 取uuid MCUUID* getUuid() { // IDA ServerNetworkHandler::_createNewPlayer return (MCUUID*)((char*)this + 2800); } // 根据地图信息获取玩家xuid std::string& getXuid(VA level) { return SYMCALL(std::string&, MSSYM_MD5_337bfad553c289ba4656ac43dcb60748, level, (char*)this + 2800); } // 重设服务器玩家名 void reName(std::string name) { SYMCALL(void, MSSYM_B1QA7setNameB1AA6PlayerB2AAA9UEAAXAEBVB2QDA5basicB1UA6stringB1AA2DUB2QDA4charB1UA6traitsB1AA1DB1AA3stdB2AAA1VB2QDA9allocatorB1AA1DB1AA12B2AAA3stdB3AAAA1Z, this, name); } // 获取网络标识符 VA getNetId() { return (VA)this + 2512; // IDA ServerPlayer::setPermissions } // 获取背包 VA getSupplies() { // IDA Player::add return *(VA*)(*((VA*)this + 378) + 176); } // 添加一个物品 void addItem(VA item) { SYMCALL(VA, MSSYM_B1QA3addB1AA6PlayerB2AAA4UEAAB1UE14NAEAVItemStackB3AAAA1Z, this, item); } // 更新所有物品列表 void updateInventory() { VA itm = (VA)this + 4568; // IDA Player::drop SYMCALL(VA, MSSYM_B1QE23forceBalanceTransactionB1AE27InventoryTransactionManagerB2AAA7QEAAXXZ, itm); } // 发送数据包 VA sendPacket(VA pkt) { return SYMCALL(VA, MSSYM_B1QE17sendNetworkPacketB1AE12ServerPlayerB2AAE15UEBAXAEAVPacketB3AAAA1Z, this, pkt); } }; #pragma endregion #pragma region Items 定义物品结构体 struct Item { // 转换id为原始标识字符 static std::string getRawNameFromId(int id) { VA* it; SYMCALL(VA, MSSYM_B1QA7getItemB1AE12ItemRegistryB2AAA2SAB1QA2AVB2QDA7WeakPtrB1AA5VItemB4AAAAA1FB1AA1Z, &it, id); if (it && *it) { return *SYMCALL(std::string*, MSSYM_MD5_2f9d68ca736b0da0c26f063f568898bc, // Item::getRawNameId *it); } return "unknow"; } }; struct ItemStackBase { VA vtable; VA mItem; VA mUserData; VA mBlock; short mAuxValue; char mCount; char mValid; char unk[4]{ 0 }; VA mPickupTime; char mShowPickUp; char unk2[7]{ 0 }; std::vector<VA*> mCanPlaceOn; VA mCanPlaceOnHash; std::vector<VA*> mCanDestroy; VA mCanDestroyHash; VA mBlockingTick; ItemStackBase* mChargedItem; VA uk; public: bool getFromId(short id, short aux, char count) { memcpy(this, SYM_POINT(void, MSSYM_B1QA5EMPTYB1UA4ITEMB1AA9ItemStackB2AAA32V1B1AA1B), 0x90); bool ret = SYMCALL(bool, MSSYM_B2QUA7setItemB1AE13ItemStackBaseB2AAA4IEAAB1UA2NHB1UA1NB1AA1Z, this, id, false); mCount = count; mAuxValue = aux; mValid = true; return ret; } }; struct ItemStack : ItemStackBase { // 取物品ID short getId() { return SYMCALL(short, MSSYM_B1QA5getIdB1AE13ItemStackBaseB2AAA7QEBAFXZ, this); } // 取物品特殊值 short getAuxValue() { return SYMCALL(short, MSSYM_B1QE11getAuxValueB1AE13ItemStackBaseB2AAA7QEBAFXZ, this); } // 取物品名称 std::string getName() { std::string str; // IDA ItemStackBase::getName SYMCALL(__int64, MSSYM_MD5_6d581a35d7ad70fd364b60c3ebe93394, this, &str); return str; } // 取物品命名空间标识 std::string getRawNameId() { std::string str; SYMCALL(VA, MSSYM_MD5_2f9d68ca736b0da0c26f063f568898bc, this, &str); return str; } // 取容器内数量 int getStackSize() { // IDA ContainerModel::networkUpdateItem return *((char*)this + 34); } // 判断是否空容器 bool isNull() { return SYMCALL(bool, MSSYM_B1QA6isNullB1AE13ItemStackBaseB2AAA4QEBAB1UA3NXZ, this); } }; struct ItemActor : Actor { // 获取实际物品 ItemStack* getItemStack() { // IDA see Hopper::_addItem return (ItemStack*)((VA)this + 1648); } }; struct LevelContainerModel { // 取开容者 Player* getPlayer() { return ((Player**)this)[26]; } }; #pragma endregion #pragma region Packets 定义数据包结构体 struct TextPacket { char filler[0xC8]; // 取输入文本 std::string toString() { // IDA ServerNetworkHandler::handle std::string str = std::string(*(std::string*)((VA)this + 80)); return str; } }; struct CommandRequestPacket { char filler[0x90]; // 取命令文本 std::string toString() { // IDA ServerNetworkHandler::handle std::string str = std::string(*(std::string*)((VA)this + 40)); return str; } }; struct ModalFormRequestPacket { char filler[0x48]; }; struct ModalFormResponsePacket { // 取发起表单ID UINT getFormId() { return *(UINT*)((VA)this + 40); } // 取选择序号 std::string getSelectStr() { std::string x = *(std::string*)((VA)this + 48); VA l = x.length(); if (x.c_str()[l - 1] == '\n') { return l > 1 ? x.substr(0, l - 1) : x; } return x; } }; #pragma endregion
14,721
C++
.h
495
24.323232
177
0.688584
zhkj-liuxiaohua/BDSNetRunner
37
8
0
LGPL-2.1
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,713
Events.h
zhkj-liuxiaohua_BDSNetRunner/BDSNetRunner/Events.h
#pragma once #include "BDS.hpp" enum class EventType : UINT16 { Nothing = 0, onServerCmd = 1, onServerCmdOutput = 2, onFormSelect = 3, onUseItem = 4, onPlacedBlock = 5, onDestroyBlock = 6, onStartOpenChest = 7, onStartOpenBarrel = 8, onStopOpenChest = 9, onStopOpenBarrel = 10, onSetSlot = 11, onChangeDimension = 12, onMobDie = 13, onMobHurt = 14, onRespawn = 15, onChat = 16, onInputText = 17, onCommandBlockUpdate = 18, onInputCommand = 19, onBlockCmd = 20, onNpcCmd = 21, onLoadName = 22, onPlayerLeft = 23, onMove = 24, onAttack = 25, onLevelExplode = 26, onEquippedArmor = 27, onLevelUp = 28, onPistonPush = 29, onChestPair = 30, onMobSpawnCheck = 31, onDropItem = 32, onPickUpItem = 33, onScoreChanged = 34, onScriptEngineInit = 35, onScriptEngineLog = 36, onScriptEngineCmd = 37, onScoreboardInit = 38 }; // 监听模式 enum class ActMode : UINT16 { BEFORE = 0, AFTER = 1 }; // 所有事件关键字 struct ACTEVENT { const std::string ONSERVERCMD = u8"onServerCmd"; const std::string ONSERVERCMDOUTPUT = u8"onServerCmdOutput"; const std::string ONFORMSELECT = u8"onFormSelect"; const std::string ONUSEITEM = u8"onUseItem"; const std::string ONMOVE = u8"onMove"; const std::string ONATTACK = u8"onAttack"; const std::string ONPLACEDBLOCK = u8"onPlacedBlock"; const std::string ONDESTROYBLOCK = u8"onDestroyBlock"; const std::string ONSTARTOPENCHEST = u8"onStartOpenChest"; const std::string ONSTARTOPENBARREL = u8"onStartOpenBarrel"; const std::string ONCHANGEDIMENSION = u8"onChangeDimension"; const std::string ONLOADNAME = u8"onLoadName"; const std::string ONPLAYERLEFT = u8"onPlayerLeft"; const std::string ONSTOPOPENCHEST = u8"onStopOpenChest"; const std::string ONSTOPOPENBARREL = u8"onStopOpenBarrel"; const std::string ONSETSLOT = u8"onSetSlot"; const std::string ONMOBDIE = u8"onMobDie"; const std::string ONRESPAWN = u8"onRespawn"; const std::string ONCHAT = u8"onChat"; const std::string ONINPUTTEXT = u8"onInputText"; const std::string ONINPUTCOMMAND = u8"onInputCommand"; const std::string ONLEVELEXPLODE = u8"onLevelExplode"; const std::string ONEQUIPPEDARMOR = u8"onEquippedArmor"; const std::string ONLEVELUP = u8"onLevelUp"; const std::string ONPISTONPUSH = u8"onPistonPush"; const std::string ONCHESTPAIR = u8"onChestPair"; const std::string ONMOBSPAWNCHECK = u8"onMobSpawnCheck"; const std::string ONDROPITEM = u8"onDropItem"; const std::string ONPICKUPITEM = u8"onPickUpItem"; const std::string ONSCORECHANGED = u8"onScoreChanged"; const std::string ONSCRIPTENGINEINIT = u8"onScriptEngineInit"; const std::string ONSCRIPTENGINELOG = u8"onScriptEngineLog"; const std::string ONSCRIPTENGINECMD = u8"onScriptEngineCmd"; const std::string ONSCOREBOARDINIT = u8"onScoreboardInit"; #if (COMMERCIAL) const std::string ONMOBHURT = u8"onMobHurt"; const std::string ONBLOCKCMD = u8"onBlockCmd"; const std::string ONNPCCMD = u8"onNpcCmd"; const std::string ONCOMMANDBLOCKUPDATE = u8"onCommandBlockUpdate"; #endif }; #pragma pack(1) struct Events { EventType type; // 事件类型 ActMode mode; // 触发模式 int result; // 事件结果(注册After事件时,此值有效) void* data; // 原始数据指针 }; #pragma pack() //////////////// 属性追加规则:追加的所有属性,必须移动到继承后事件属性末尾,保证兼容性 //////////////// struct ServerCmdEvent { char* cmd; // 指令数据 public: ServerCmdEvent() { memset(this, 0, sizeof(ServerCmdEvent)); } void releaseAll() { if (cmd) { delete cmd; cmd = NULL; } } }; struct ServerCmdOutputEvent { char* output; // 输出信息 public: ServerCmdOutputEvent() { memset(this, 0, sizeof(ServerCmdOutputEvent)); } void releaseAll() { if (output) { delete output; output = NULL; } } }; struct PlayerEvent { char* playername; // 玩家名字 char* dimension; // 玩家所在维度 Vec3 XYZ; // 玩家所处位置 int dimensionid; // 玩家所在维度ID bool isstand; // 玩家是否立足于方块/悬空 public: PlayerEvent() { memset(this, 0, sizeof(PlayerEvent)); } void releaseAll() { if (playername) { delete playername; playername = NULL; } if (dimension) { delete dimension; dimension = NULL; } } }; struct FormSelectEvent : PlayerEvent { char* uuid; // 玩家uuid信息 char* selected; // 表单回传的选择项信息 int formid; // 表单ID void* pplayer; // 附加组件,玩家指针 public: FormSelectEvent() { memset(this, 0, sizeof(FormSelectEvent)); } void releaseAll() { if (uuid) { delete uuid; uuid = NULL; } if (selected) { delete selected; selected = NULL; } ((PlayerEvent*)this)->releaseAll(); } }; struct UseItemEvent : PlayerEvent { char* itemname; // 物品名称 BPos3 position; // 操作方块所在位置 short itemid; // 物品ID short itemaux; // 物品特殊值 char* blockname; // 操作方块名称 short blockid; // 操作方块ID void* pplayer; // 附加组件,玩家指针 public: UseItemEvent() { memset(this, 0, sizeof(UseItemEvent)); } void releaseAll() { if (itemname) { delete itemname; itemname = NULL; } if (blockname) { delete blockname; blockname = NULL; } ((PlayerEvent*)this)->releaseAll(); } }; struct BlockEvent : PlayerEvent { char* blockname; // 方块名称 BPos3 position; // 操作方块所在位置 short blockid; // 方块ID void* pplayer; // 附加组件,玩家指针 public: BlockEvent() { memset(this, 0, sizeof(BlockEvent)); } void releaseAll() { if (blockname) { delete blockname; blockname = NULL; } ((PlayerEvent*)this)->releaseAll(); } }; struct PlacedBlockEvent : BlockEvent { }; struct DestroyBlockEvent : BlockEvent { }; struct StartOpenChestEvent : BlockEvent { }; struct StartOpenBarrelEvent : BlockEvent { }; struct StopOpenChestEvent : BlockEvent { }; struct StopOpenBarrelEvent : BlockEvent { }; struct SetSlotEvent : PlayerEvent { char* itemname; // 物品名字 char* blockname; // 方块名称 BPos3 position; // 操作方块所在位置 int itemcount; // 物品数量 int slot; // 操作格子位置 short itemaux; // 物品特殊值 short blockid; // 方块ID short itemid; // 物品ID void* pplayer; // 附加组件,玩家指针 public: SetSlotEvent() { memset(this, 0, sizeof(SetSlotEvent)); } void releaseAll() { if (itemname) { delete itemname; itemname = NULL; } if (blockname) { delete blockname; blockname = NULL; } ((PlayerEvent*)this)->releaseAll(); } }; struct ChangeDimensionEvent : PlayerEvent { void* pplayer; // 附加组件,玩家指针 }; struct MobDieBaseEvent { char* mobname; // 生物名称 char* playername; // 玩家名字(若为玩家死亡,附加此信息) char* dimension; // 玩家所在维度(附加信息) char* mobtype; // 生物类型 char* srcname; // 伤害源名称 char* srctype; // 伤害源类型 Vec3 XYZ; // 生物所在位置 int dimensionid; // 生物所处维度ID int dmcase; // 伤害具体原因ID bool isstand; // 玩家是否立足于方块/悬空(附加信息) public: MobDieBaseEvent() { memset(this, 0, sizeof(MobDieBaseEvent)); } void releaseAll() { if (mobname) { delete mobname; mobname = NULL; } if (playername) { delete playername; playername = NULL; } if (dimension) { delete dimension; dimension = NULL; } if (mobtype) { delete mobtype; mobtype = NULL; } if (srcname) { delete srcname; srcname = NULL; } if (srctype) { delete srctype; srctype = NULL; } } }; struct MobDieEvent : MobDieBaseEvent { void* pmob; // 附加组件,玩家指针 }; struct MobHurtEvent : MobDieBaseEvent { char* dmtype; // 生物受伤类型 float health; // 生物血量 int dmcount; // 生物受伤具体值 void* pmob; // 附加组件,生物指针 public: MobHurtEvent() { memset(this, 0, sizeof(MobHurtEvent)); } void releaseAll() { if (dmtype) { delete dmtype; dmtype = NULL; } ((MobDieEvent*)this)->releaseAll(); } }; struct RespawnEvent : PlayerEvent { void* pplayer; // 附加组件,玩家指针 }; struct ChatEvent { char* playername; // 发言人名字(可能为服务器或命令方块发言) char* target; // 接收者名字 char* msg; // 接收到的信息 char* chatstyle; // 聊天类型 public: ChatEvent() { memset(this, 0, sizeof(ChatEvent)); } void releaseAll() { if (playername) { delete playername; playername = NULL; } if (target) { delete target; target = NULL; } if (msg) { delete msg; msg = NULL; } if (chatstyle) { delete chatstyle; chatstyle = NULL; } } }; struct InputTextEvent : PlayerEvent { char* msg; // 输入的文本 void* pplayer; // 附加组件,玩家指针 public: InputTextEvent() { memset(this, 0, sizeof(InputTextEvent)); } void releaseAll() { if (msg) { delete msg; msg = NULL; } ((PlayerEvent*)this)->releaseAll(); } }; struct CommandBlockUpdateEvent : PlayerEvent { char* cmd; // 将被更新的新指令 char* actortype;// 实体类型(若被更新的是非方块,附加此信息) BPos3 position; // 命令方块所在位置 bool isblock; // 是否是方块 void* pplayer; // 附加组件,玩家指针 public: CommandBlockUpdateEvent() { memset(this, 0, sizeof(CommandBlockUpdateEvent)); } void releaseAll() { if (cmd) { delete cmd; cmd = NULL; } if (actortype) { delete actortype; actortype = NULL; } ((PlayerEvent*)this)->releaseAll(); } }; struct InputCommandEvent : PlayerEvent { char* cmd; // 玩家输入的指令 void* pplayer; // 附加组件,玩家指针 public: InputCommandEvent() { memset(this, 0, sizeof(InputCommandEvent)); } void releaseAll() { if (cmd) { delete cmd; cmd = NULL; } ((PlayerEvent*)this)->releaseAll(); } }; struct BlockCmdEvent { char* cmd; // 将被执行的指令 char* name; // 执行者自定义名称 char* dimension;// 命令块所处维度 BPos3 position; // 执行者所在位置 int dimensionid;// 命令块所处维度ID int tickdelay; // 命令设定的间隔时间 int type; // 执行者类型 public: BlockCmdEvent() { memset(this, 0, sizeof(BlockCmdEvent)); } void releaseAll() { if (cmd) { delete cmd; cmd = NULL; } if (name) { delete name; name = NULL; } if (dimension) { delete dimension; dimension = NULL; } } }; struct NpcCmdEvent { char* npcname; // NPC名字 char* entity; // NPC实体标识名 char* dimension; // NPC所处维度 char* actions; // 指令列表 Vec3 position; // NPC所在位置 int actionid; // 选择项 int entityid; // NPC实体标识ID int dimensionid; // NPC所处维度ID void* pnpc; // 附加组件,npc指针 void* ptrigger; // 附加组件,触发者player指针 public: NpcCmdEvent() { memset(this, 0, sizeof(NpcCmdEvent)); } void releaseAll() { if (npcname) { delete npcname; npcname = NULL; } if (entity) { delete entity; entity = NULL; } if (dimension) { delete dimension; dimension = NULL; } if (actions) { delete actions; actions = NULL; } } }; struct LoadNameEvent { char* playername; // 玩家名字 char* uuid; // 玩家uuid字符串 char* xuid; // 玩家xuid字符串 char* ability; // 玩家能力值列表(可选,商业版可用) void* pplayer; // 附加组件,玩家指针 public: LoadNameEvent() { memset(this, 0, sizeof(LoadNameEvent)); } void releaseAll() { if (playername) { delete playername; playername = NULL; } if (uuid) { delete uuid; uuid = NULL; } if (xuid) { delete xuid; xuid = NULL; } if (ability) { delete ability; ability = NULL; } } }; struct PlayerLeftEvent : LoadNameEvent { }; struct MoveEvent : PlayerEvent { void* pplayer; // 附加组件,玩家指针 }; struct AttackEvent : PlayerEvent { char* actorname; // 被攻击实体名称 char* actortype; // 被攻击实体类型 Vec3 actorpos; // 被攻击实体所处位置 void* pattacker; // 附加组件,玩家指针 void* pattackedentity; // 附加组件,被攻击实体指针 int damagecause; // 攻击伤害类型 public: AttackEvent() { memset(this, 0, sizeof(AttackEvent)); } void releaseAll() { if (actorname) { delete actorname; actorname = NULL; } if (actortype) { delete actortype; actortype = NULL; } ((PlayerEvent*)this)->releaseAll(); } }; struct LevelExplodeEvent { char* entity; // 爆炸者实体标识名(可能为空) char* blockname; // 爆炸方块名(可能为空) char* dimension; // 爆炸者所处维度 Vec3 position; // 爆炸点所在位置 int entityid; // 爆炸者实体标识ID int dimensionid; // 爆炸者所处维度ID float explodepower; // 爆炸强度 short blockid; // 爆炸方块ID public: LevelExplodeEvent() { memset(this, 0, sizeof(LevelExplodeEvent)); } void releaseAll() { if (entity) { delete entity; entity = NULL; } if (dimension) { delete dimension; dimension = NULL; } } }; struct EquippedArmorEvent : PlayerEvent { char* itemname; // 物品名字 int itemcount; // 物品数量 int slot; // 操作格子位置 short itemaux; // 物品特殊值 short itemid; // 物品ID short slottype; // 切换的装备类型,0 - 护甲类,1 - 主副手 void* pplayer; // 附加组件,玩家指针 public: EquippedArmorEvent() { memset(this, 0, sizeof(EquippedArmorEvent)); } void releaseAll() { if (itemname) { delete itemname; itemname = NULL; } } }; struct LevelUpEvent : PlayerEvent { void* pplayer; // 附加组件,玩家指针 int lv; // 玩家等级 public: LevelUpEvent() { memset(this, 0, sizeof(LevelUpEvent)); } void releaseAll() { ((PlayerEvent*)this)->releaseAll(); } }; struct ChestPairEvent { char* dimension; // 方块所处维度 char* blockname; // 活塞方块名称 char* targetblockname; // 被推方块名称 BPos3 position; // 活塞方块所在位置 BPos3 targetposition; // 被推目标方块所在位置 int dimensionid; // 方块所处维度ID short blockid; // 活塞方块ID short targetblockid; // 被推目标方块ID public: ChestPairEvent() { memset(this, 0, sizeof(ChestPairEvent)); } void releaseAll() { if (dimension) { delete dimension; dimension = NULL; } if (blockname) { delete blockname; blockname = NULL; } if (targetblockname) { delete targetblockname; targetblockname = NULL; } } }; struct PistonPushEvent : ChestPairEvent { UINT8 direction; // 朝向 public: PistonPushEvent() { memset(this, 0, sizeof(PistonPushEvent)); } }; struct MobSpawnCheckEvent { char* mobname; // 生物名称 char* dimension; // 生物所在维度 char* mobtype; // 生物类型 Vec3 XYZ; // 生物所在位置 int dimensionid; // 生物所处维度ID void* pmob; // 生物指针 public: MobSpawnCheckEvent() { memset(this, 0, sizeof(MobSpawnCheckEvent)); } void releaseAll() { if (mobname) { delete mobname; mobname = NULL; } if (dimension) { delete dimension; dimension = NULL; } if (mobtype) { delete mobtype; mobtype = NULL; } } }; struct PickUpItemEvent : PlayerEvent { char* itemname; // 物品名称 short itemid; // 物品ID short itemaux; // 物品特殊值 void* pplayer; // 附加组件,生物组件 public: PickUpItemEvent() { memset(this, 0, sizeof(PickUpItemEvent)); } void releaseAll() { if (itemname) { delete itemname; itemname = NULL; } } }; struct ScoreChangedEvent { char* objectivename; // 计分板名称 char* displayname; // 计分板显示名 __int64 scoreboardid; // 计分板ID值 int score; // 分数 public: ScoreChangedEvent() { memset(this, 0, sizeof(ScoreChangedEvent)); } void releaseAll() { if (objectivename) { delete objectivename; objectivename = NULL; } if (displayname) { delete displayname; displayname = NULL; } } }; struct ScriptEngineInitEvent { VA jsen; // 官方脚本引擎指针 public: ScriptEngineInitEvent() { memset(this, 0, sizeof(ScriptEngineInitEvent)); } }; struct ScriptEngineLogEvent : ScriptEngineInitEvent { char* log; // 官方脚本引擎log输出信息 public: ScriptEngineLogEvent() { memset(this, 0, sizeof(ScriptEngineLogEvent)); } void releaseAll() { if (log) { delete log; log = NULL; } } }; struct ScriptEngineCmdEvent : ScriptEngineLogEvent { }; struct ScoreboardInitEvent { VA scptr; // 系统计分板指针 public: ScoreboardInitEvent() { memset(this, 0, sizeof(ScoreboardInitEvent)); } };
16,472
C++
.h
695
18.87482
70
0.668635
zhkj-liuxiaohua/BDSNetRunner
37
8
0
LGPL-2.1
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,715
mod.h
zhkj-liuxiaohua_BDSNetRunner/BDSNetRunner/mod.h
#pragma once #include "Events.h" // 社区版/商业版 #define COMMERCIAL 0 // 标识贡献者 05007 #define MODULE_05007 1 // 标识贡献者 kengwang #define MODULE_KENGWANG 1 extern void init(); extern void exit(); extern void initMods(); #define MCCSAPI extern "C" __declspec (dllexport) #define MCCPPAPI extern "C" __declspec (dllexport) // 设置c#一个通用指针 MCCSAPI void setSharePtr(const char*, void*); // 获取c#一个通用指针 MCCSAPI void* getSharePtr(const char*); // 移除c#一个通用指针 MCCSAPI void* removeSharePtr(const char*); // 注册c#事件发生前回调 MCCSAPI bool addBeforeActListener(const char*, bool(*)(Events)); // 注册c#事件发生后回调 MCCSAPI bool addAfterActListener(const char*, bool(*)(Events)); // 移除c#事件发生前回调 MCCSAPI bool removeBeforeActListener(const char*, bool(*)(Events)); // 移除c#事件发生后回调 MCCSAPI bool removeAfterActListener(const char*, bool(*)(Events)); // 设置一个全局指令说明 MCCSAPI void setCommandDescribeEx(const char*, const char*, char, char, char); // 执行后端指令 MCCSAPI bool runcmd(const char*); // 发送一个命令输出消息(末尾接换行符) MCCSAPI void logout(const char*); // 获取在线玩家列表 MCCSAPI std::string getOnLinePlayers(); // 重设新名字 MCCSAPI bool reNameByUuid(const char*, const char*); // 获取一个在线玩家信息 MCCSAPI std::string selectPlayer(const char*); // 模拟喊话 MCCSAPI bool talkAs(const char*, const char*); // 模拟指令 MCCSAPI bool runcmdAs(const char*, const char*); // 发送指定玩家一个表单 MCCSAPI UINT sendSimpleForm(char*, char*, char*, char*); // 发送指定玩家一个模板对话框 MCCSAPI UINT sendModalForm(char*, char*, char*, char*, char*); // 发送指定玩家一个自定义GUI界面 MCCSAPI UINT sendCustomForm(char*, char*); // 销毁已使用的id MCCSAPI bool releaseForm(unsigned); // 增加玩家一个简单物品 MCCSAPI bool addPlayerItem(const char*, int, short, char); // 断开一个在线玩家的连接 MCCSAPI bool disconnectClient(const char*, const char*); // 发送给玩家一个文本 MCCSAPI bool sendText(const char*, const char*); // 请求执行一段行为包脚本 MCCSAPI void JSErunScript(const char*, void(*)(bool)); // 请求发送一个自定义行为包脚本事件广播 MCCSAPI void JSEfireCustomEvent(const char*, const char*, void(*)(bool)); // 获取物品原始标识字符 MCCSAPI std::string getItemRawname(int); // 获取离线计分板值 MCCSAPI int getscoreById(__int64, const char*); // 设置离线计分板值 MCCSAPI int setscoreById(__int64, const char*, int); // 发送一个方法至tick MCCSAPI void postTick(void(*)()); // 从此处获取额外API MCCSAPI void* getExtraAPI(const char*); // 从此处获取类组件的相关方法 MCCSAPI void* mcComponentAPI(const char*); // 来自社区贡献 #if MODULE_05007 // 获取计分板值 MCCPPAPI int getscoreboard(Player*, std::string); // C#可用获取计分板值 MCCSAPI int getscoreboardValue(const char*, const char*); // 设置计分板值 MCCPPAPI bool setscoreboard(Player*, std::string, int); // C#可用设置计分板值 MCCSAPI bool setscoreboardValue(const char*, const char*, int); #endif #if MODULE_KENGWANG // 设置服务器的显示名信息 MCCSAPI bool setServerMotd(const char*, bool); #endif #if (COMMERCIAL) // 调用原型:获取一个结构 typedef std::string (**getStructureFunc)(int, const char*, const char*, bool, bool); // 调用原型:设置一个结构到指定位置 typedef bool (**setStructureFunc)(const char*, int, const char*, char, bool, bool); // 调用原型:获取玩家能力表 typedef std::string (**getPlayerAbilitiesFunc)(const char*); // 调用原型:设置玩家能力表 typedef bool (**setPlayerAbilitiesFunc)(const char*, const char*); // 调用原型:获取玩家属性表 typedef std::string (**getPlayerAttributesFunc)(const char*); // 调用原型:设置玩家属性临时值表 typedef bool (**setPlayerTempAttributesFunc)(const char*, const char*); // 调用原型:获取玩家属性上限值表 typedef std::string (**getPlayerMaxAttributesFunc)(const char*); // 调用原型:设置玩家属性上限值表 typedef bool (**setPlayerMaxAttributesFunc)(const char*, const char*); // 调用原型:获取玩家所有物品列表 typedef std::string (**getPlayerItemsFunc)(const char*); // 调用原型:设置玩家所有物品列表 typedef bool (**setPlayerItemsFunc)(const char*, const char*); // 调用原型:获取玩家当前选中项信息 typedef std::string (**getPlayerSelectedItemFunc)(const char*); // 调用原型:增加玩家一个物品 typedef bool (**addPlayerItemExFunc)(const char*, const char*); // 调用原型:获取玩家所有效果列表 typedef std::string (**getPlayerEffectsFunc)(const char*); // 调用原型:设置玩家所有效果列表 typedef bool (**setPlayerEffectsFunc)(const char*, const char*); // 调用原型:设置玩家自定义血条 typedef bool (**setPlayerBossBarFunc)(const char*, const char*, float); // 调用原型:清除玩家自定义血条 typedef bool (**removePlayerBossBarFunc)(const char*); // 调用原型:传送玩家至指定服务器 typedef bool (**transferserverFunc)(const char*, const char*, int); // 调用原型:传送玩家至指定坐标和维度 typedef bool (**teleportFunc)(const char*, float, float, float, int); // 调用原型:设置玩家自定义侧边栏临时计分板 typedef bool (**setPlayerSidebarFunc)(const char*, const char*, const char*); // 调用原型:清除玩家自定义侧边栏 typedef bool (**removePlayerSidebarFunc)(const char*); // 调用原型:获取玩家权限与游戏模式 typedef std::string (**getPlayerPermissionAndGametypeFunc)(const char*); // 调用原型:设置玩家权限与游戏模式 typedef bool (**setPlayerPermissionAndGametypeFunc)(const char*, const char*); // 调用原型:获取所有计分板计分项 typedef std::string(**getAllScoreFunc)(); // 调用原型:设置所有计分板计分项 typedef bool (**setAllScoreFunc)(const char*); // 调用原型:获取地图所处位置区块颜色数据 typedef std::string(**getMapColorsFunc)(int, int, int, int); // 调用原型:导出地图所有离线玩家数据 typedef std::string(**exportPlayersDataFunc)(); // 调用原型:导入玩家数据至地图 typedef bool(**importPlayersDataFunc)(const char*); #endif // 返回实际RVA对应地址 MCCSAPI unsigned long long dlsym(int rva); // 注册c#可用的hook函数 MCCSAPI bool cshook(int rva, void* hook, void** org); // 注册c#可用的unhook函数 MCCSAPI bool csunhook(void* hook, void** org); // 读特定段内存硬编码 MCCSAPI bool readHardMemory(int rva, unsigned char* odata, int size); // 写特定段内存硬编码 MCCSAPI bool writeHardMemory(int rva, unsigned char* ndata, int size);
6,267
C++
.h
154
33.422078
85
0.750236
zhkj-liuxiaohua/BDSNetRunner
37
8
0
LGPL-2.1
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,716
Component.h
zhkj-liuxiaohua_BDSNetRunner/BDSNetRunner/Component.h
#pragma once #include<string> // 实体组件Flag相关 // 操作类型 enum class ActorDataIDs : char { FLAGS = 0, STRUCTURAL_INTEGRITY = 1, VARIANT = 2, COLOR_INDEX = 3, NAME = 4, OWNER = 5, TARGET = 6, AIR_SUPPLY = 7, EFFECT_COLOR = 8, EFFECT_AMBIENCE = 9, JUMP_DURATION = 0x0A, HURT = 0x0B, HURT_DIR = 0x0C, ROW_TIME_LEFT = 0x0D, ROW_TIME_RIGHT = 0x0E, VALUE = 0x0F, DISPLAY_TILE_RUNTIME_ID = 0x10, DISPLAY_OFFSET = 0x11, CUSTOM_DISPLAY = 0x12, SWELL = 0x13, OLD_SWELL = 0x14, SWELL_DIR = 0x15, CHARGE_AMOUNT = 0x16, CARRY_BLOCK_RUNTIME_ID = 0x17, CLIENT_EVENT = 0x18, USING_ITEM = 0x19, PLAYER_FLAGS = 0x1A, PLAYER_INDEX = 0x1B, BED_POSITION = 0x1C, X_POWER = 0x1D, Y_POWER = 0x1E, Z_POWER = 0x1F, AUX_POWER = 0x20, FISHX = 0x21, FISHZ = 0x22, FISHANGLE = 0x23, AUX_VALUE_DATA = 0x24, LEASH_HOLDER = 0x25, SCALE = 0x26, HAS_NPC = 0x27, NPC_DATA = 0x28, ACTIONS = 0x29, AIR_SUPPLY_MAX = 0x2A, MARK_VARIANT = 0x2B, CONTAINER_TYPE = 0x2C, CONTAINER_SIZE = 0x2D, CONTAINER_STRENGTH_MODIFIER = 0x2E, BLOCK_TARGET = 0x2F, INV = 0x30, TARGET_A = 0x31, TARGET_B = 0x32, TARGET_C = 0x33, AERIAL_ATTACK = 0x34, WIDTH = 0x35, HEIGHT = 0x36, FUSE_TIME = 0x37, SEAT_OFFSET = 0x38, SEAT_LOCK_RIDER_ROTATION = 0x39, SEAT_LOCK_RIDER_ROTATION_DEGREES = 0x3A, SEAT_ROTATION_OFFSET = 0x3B, DATA_RADIUS = 0x3C, DATA_WAITING = 0x3D, DATA_PARTICLE = 0x3E, PEEK_ID = 0x3F, ATTACH_FACE = 0x40, ATTACHED = 0x41, ATTACH_POS = 0x42, TRADE_TARGET = 0x43, CAREER = 0x44, HAS_COMMAND_BLOCK = 0x45, COMMAND_NAME = 0x46, LAST_COMMAND_OUTPUT = 0x47, TRACK_COMMAND_OUTPUT = 0x48, CONTROLLING_SEAT_INDEX = 0x49, STRENGTH = 0x4A, STRENGTH_MAX = 0x4B, DATA_SPELL_CASTING_COLOR = 0x4C, DATA_LIFETIME_TICKS = 0x4D, POSE_INDEX = 0x4E, DATA_TICK_OFFSET = 0x4F, NAMETAG_ALWAYS_SHOW = 0x50, COLOR_2_INDEX = 0x51, NAME_AUTHOR = 0x52, SCORE = 0x53, BALLOON_ANCHOR = 0x54, PUFFED_STATE = 0x55, BUBBLE_TIME = 0x56, AGENT = 0x57, SITTING_AMOUNT = 0x58, SITTING_AMOUNT_PREVIOUS = 0x59, EATING_COUNTER = 0x5A, FLAGS2 = 0x5B, LAYING_AMOUNT = 0x5C, LAYING_AMOUNT_PREVIOUS = 0x5D, DATA_DURATION = 0x5E, DATA_SPAWN_TIME = 0x5F, DATA_CHANGE_RATE = 0x60, DATA_CHANGE_ON_PICKUP = 0x61, DATA_PICKUP_COUNT = 0x62, INTERACT_TEXT = 0x63, TRADE_TIER = 0x64, MAX_TRADE_TIER = 0x65, TRADE_EXPERIENCE = 0x66, SKIN_ID = 0x67, SPAWNING_FRAMES = 0x68, COMMAND_BLOCK_TICK_DELAY = 0x69, COMMAND_BLOCK_EXECUTE_ON_FIRST_TICK = 0x6A, AMBIENT_SOUND_INTERVAL = 0x6B, AMBIENT_SOUND_INTERVAL_RANGE = 0x6C, AMBIENT_SOUND_EVENT_NAME = 0x6D, FALL_DAMAGE_MULTIPLIER = 0x6E, NAME_RAW_TEXT = 0x6F, CAN_RIDE_TARGET = 0x70 }; // 实体类型 enum class ActorType : signed { Undefined_2 = 1, ItemEntity = 0x40, PrimedTnt = 0x41, FallingBlock = 0x42, MovingBlock = 0x43, Experience = 0x45, EyeOfEnder = 0x46, EnderCrystal = 0x47, FireworksRocket = 0x48, FishingHook = 0x4D, Chalkboard = 0x4E, Painting = 0x53, LeashKnot = 0x58, BoatRideable = 0x5A, LightningBolt = 0x5D, AreaEffectCloud = 0x5F, Balloon = 0x6B, Shield = 0x75, Lectern = 0x77, TypeMask = 0x0FF, Mob = 0x100, Npc = 0x133, Agent = 0x138, ArmorStand = 0x13D, TripodCamera = 0x13E, Player_0 = 0x13F, Bee = 0x17A, PathfinderMob = 0x300, IronGolem = 0x314, SnowGolem = 0x315, WanderingTrader = 0x376, Monster = 0x0B00, Creeper = 0x0B21, Slime = 0x0B25, EnderMan = 0x0B26, Ghast = 0x0B29, LavaSlime = 0x0B2A, Blaze = 0x0B2B, Witch = 0x0B2D, Guardian = 0x0B31, ElderGuardian = 0x0B32, Dragon = 0x0B35, Shulker = 0x0B36, Vindicator = 0x0B39, IllagerBeast = 0x0B3B, EvocationIllager = 0x0B68, Vex = 0x0B69, Pillager = 0x0B72, ElderGuardianGhost = 0x0B78, Animal = 0x1300, Chicken = 0x130A, Cow = 0x130B, Pig = 0x130C, Sheep = 0x130D, MushroomCow = 0x1310, Rabbit = 0x1312, PolarBear = 0x131C, Llama = 0x131D, Turtle = 0x134A, Panda = 0x1371, Fox = 0x1379, WaterAnimal = 0x2300, Squid = 0x2311, Dolphin = 0x231F, Pufferfish = 0x236C, Salmon = 0x236D, Tropicalfish = 0x236F, Fish = 0x2370, TamableAnimal = 0x5300, Wolf = 0x530E, Ocelot = 0x5316, Parrot = 0x531E, Cat = 0x534B, Ambient = 0x8100, Bat = 0x8113, UndeadMob = 0x10B00, PigZombie = 0x10B24, WitherBoss = 0x10B34, Phantom = 0x10B3A, ZombieMonster = 0x30B00, Zombie = 0x30B20, ZombieVillager = 0x30B2C, Husk = 0x30B2F, Drowned = 0x30B6E, ZombieVillagerV2 = 0x30B74, Arthropod = 0x40B00, Spider = 0x40B23, Silverfish = 0x40B27, CaveSpider = 0x40B28, Endermite = 0x40B37, Minecart = 0x80000, MinecartRideable = 0x80054, MinecartHopper = 0x80060, MinecartTNT = 0x80061, MinecartChest = 0x80062, MinecartFurnace = 0x80063, MinecartCommandBlock = 0x80064, SkeletonMonster = 0x110B00, Skeleton = 0x110B22, Stray = 0x110B2E, WitherSkeleton = 0x110B30, EquineAnimal = 0x205300, Horse = 0x205317, Donkey = 0x205318, Mule = 0x205319, SkeletonHorse = 0x215B1A, ZombieHorse = 0x215B1B, Projectile = 0x400000, ExperiencePotion = 0x400044, ShulkerBullet = 0x40004C, DragonFireball = 0x40004F, Snowball = 0x400051, ThrownEgg = 0x400052, LargeFireball = 0x400055, ThrownPotion = 0x400056, Enderpearl = 0x400057, WitherSkull = 0x400059, WitherSkullDangerous = 0x40005B, SmallFireball = 0x40005E, LingeringPotion = 0x400065, LlamaSpit = 0x400066, EvocationFang = 0x400067, IceBomb = 0x40006A, AbstractArrow = 0x800000, Trident = 0x0C00049, Arrow = 0x0C00050, VillagerBase = 0x1000300, Villager = 0x100030F, VillagerV2 = 0x1000373 }; // 伤害原因 enum class ActorDamageCause : int { Override = 0x0, Contact = 0x1, EntityAttack = 0x2, Projectile = 0x3, Suffocation = 0x4, Fall = 0x5, Fire = 0x6, FireTick = 0x7, Lava = 0x8, Drowning = 0x9, BlockExplosion = 0x0A, EntityExplosion = 0x0B, Void = 0x0C, Suicide = 0x0D, Magic = 0x0E, Wither = 0x0F, Starve = 0x10, Anvil = 0x11, Thorns = 0x12, FallingBlock = 0x13, Piston = 0x14, FlyIntoWall = 0x15, Magma = 0x16, Fireworks = 0x17, Lightning = 0x18, Charging = 0x19, Temperature = 0x1A, All = 0x1F, None = -0x01, }; struct ActorDamageByActorSource { char fill[0x50]; // IDA ActorDamageByActorSource::clone }; // 各类组件获取和设置关键字 struct MCMETHOD { const std::string ENTITY_GET_ARMOR_CONTAINER = "entity.get_armor_container"; const std::string ENTITY_GET_ATTACK = "entity.get_attack"; const std::string ENTITY_SET_ATTACK = "entity.set_attack"; const std::string ENTITY_GET_COLLISION_BOX = "entity.get_collision_box"; const std::string ENTITY_SET_COLLISION_BOX = "entity.set_collision_box"; const std::string ENTITY_GET_HAND_CONTAINER = "entity.get_hand_container"; const std::string ENTITY_GET_HEALTH = "entity.get_health"; const std::string ENTITY_SET_HEALTH = "entity.set_health"; const std::string ENTITY_GET_INVENTORY_CONTAINER = "entity.get_inventory_container"; const std::string ENTITY_GET_NAME = "entity.get_name"; const std::string ENTITY_SET_NAME = "entity.set_name"; const std::string ENTITY_GET_POSITION = "entity.get_position"; const std::string ENTITY_SET_POSITION = "entity.set_position"; const std::string ENTITY_GET_ROTATION = "entity.get_rotation"; const std::string ENTITY_SET_ROTATION = "entity.set_rotation"; const std::string ENTITY_GET_DIMENSIONID = "entity.get_dimensionid"; const std::string ENTITY_GET_TYPEID = "entity.get_typeid"; const std::string ENTITY_GET_UNIQUEID = "entity.get_uniqueid"; const std::string ENTITY_REMOVE = "entity.remove"; const std::string ENTITY_HURT = "entity.hurt"; const std::string LEVEL_GETFROM_UNIQUEID = "level.getfrom_uniqueid"; const std::string LEVEL_GETSFROM_AABB = "level.getsfrom_aabb"; const std::string LEVEL_GETPLFROM_AABB = "level.getplfrom_aabb"; const std::string PLAYER_GET_HOTBAR_CONTAINER = "player.get_hotbar_container"; const std::string PLAYER_GET_UUID = "player.get_uuid"; const std::string PLAYER_GET_IPPORT = "player.get_ipport"; const std::string PLAYER_ADD_LEVEL = "player.add_level"; const std::string PLAYER_GET_SCOREID = "player.get_scoreboardid"; const std::string PLAYER_CREATE_SCOREID = "player.create_scoreboardid"; const std::string PLAYER_GET_STORAGEID = "player.get_storageid"; };
8,128
C++
.h
319
23.413793
85
0.739802
zhkj-liuxiaohua/BDSNetRunner
37
8
0
LGPL-2.1
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,717
version.h
zhkj-liuxiaohua_BDSNetRunner/BDSNetRunner/json/include/json/version.h
#ifndef JSON_VERSION_H_INCLUDED #define JSON_VERSION_H_INCLUDED // Note: version must be updated in three places when doing a release. This // annoying process ensures that amalgamate, CMake, and meson all report the // correct version. // 1. /meson.build // 2. /include/json/version.h // 3. /CMakeLists.txt // IMPORTANT: also update the SOVERSION!! #define JSONCPP_VERSION_STRING "1.9.3" #define JSONCPP_VERSION_MAJOR 1 #define JSONCPP_VERSION_MINOR 9 #define JSONCPP_VERSION_PATCH 3 #define JSONCPP_VERSION_QUALIFIER #define JSONCPP_VERSION_HEXA \ ((JSONCPP_VERSION_MAJOR << 24) | (JSONCPP_VERSION_MINOR << 16) | \ (JSONCPP_VERSION_PATCH << 8)) #ifdef JSONCPP_USING_SECURE_MEMORY #undef JSONCPP_USING_SECURE_MEMORY #endif #define JSONCPP_USING_SECURE_MEMORY 0 // If non-zero, the library zeroes any memory that it has allocated before // it frees its memory. #endif // JSON_VERSION_H_INCLUDED
966
C++
.h
24
38.875
80
0.720682
zhkj-liuxiaohua/BDSNetRunner
37
8
0
LGPL-2.1
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
1,541,725
scoreboard.hpp
zhkj-liuxiaohua_BDSNetRunner/BDSNetRunner/scoreboard/scoreboard.hpp
#pragma once #include "../mod.h" #if (MODULE_05007) //结构体=============================================================================================================== //摘自计分板转bdxmoney项目:https://github.com/kkj9333/BDS-- //原作者:starkc //函数=========================================================================== //获取计分板内容 struct ScoreboardId { // __int64 getId() { return *(__int64*)this; } }; struct PlayerScoreboardId { // }; struct PlayerScore { // *(_QWORD *)this = *(_QWORD *)a2;//ScoreboardId *a2 //*((_QWORD*)this + 1) = *((_QWORD*)a2 + 1); // *((_DWORD *)this + 4) = int; auto getscore() { return *((__int64*)this + 4); } }; struct ScoreInfo { //scoreboardcmd list; objective::objective; scoreboard getscores //int scores +12 this[12] // std::string displayname +96 //std::string name +64 auto getcount() { return *(int*)((VA)(this) + 12); } }; struct Objective { auto getscoreinfo(ScoreInfo* a1, ScoreboardId* a2) { return SYMCALL(ScoreInfo*, MSSYM_B1QE14getPlayerScoreB1AA9ObjectiveB2AAA4QEBAB1QE11AUScoreInfoB2AAE16AEBUScoreboardIdB3AAAA1Z, this, a1, a2); } auto getplayerscoreinfo(ScoreInfo* a1, PlayerScoreboardId* a2) { return SYMCALL(ScoreInfo*, MSSYM_B1QE14getPlayerScoreB1AA9ObjectiveB2AAA4QEBAB1QE11AUScoreInfoB2AAE16AEBUScoreboardIdB3AAAA1Z, this, a1, a2); } //获取计分板名称 auto getscorename() { // IDA Objective::Objective return *(std::string*)((VA)this + 64); } //获取计分板展示名称 auto getscoredisplayname() { return *(std::string*)((VA)this + 96); } }; struct IdentityDictionary { //4个unmap auto getScoreboardID(PlayerScoreboardId* a2) { return SYMCALL(ScoreboardId*, MSSYM_MD5_6f6eac4360ca6db559c6b6e16774f7fa, this, a2, this); } }; struct ScoreboardIdentityRef { //bool请设置为1; a6=0 set,a6=1,add,a6=2,remove bool modifiedscores(Objective* obj, __int64 num, unsigned __int8 setfun) { int v25 = 0; int nums = static_cast<int>(num); return SYMCALL(bool, MSSYM_B1QE22modifyScoreInObjectiveB1AE21ScoreboardIdentityRefB2AAA4QEAAB1UE18NAEAHAEAVObjectiveB2AAE25HW4PlayerScoreSetFunctionB3AAAA1Z, this, &v25, obj, nums, setfun); } }; struct Scoreboard { VA getObjective(std::string x) { return SYMCALL(VA, MSSYM_MD5_844f126769868c7d0ef42725c3859954, this, x); } VA addObjective(std::string x, std::string t) { std::string d = "dummy"; auto v13 = GetModuleHandleW(0); VA v15 = ((VA(*)(VA, VA))(v13 + 4688112))((VA)this, (VA)&d); VA result = ((VA(*)(VA, VA, VA, VA))(v13 + 4687888))((VA)this, (VA)&x, (VA)&t, v15); return result; } VA createPlayerScoreboardId(Player* a) { return SYMCALL(VA, MSSYM_B1QE18createScoreboardIdB1AE16ServerScoreboardB2AAE20UEAAAEBUScoreboardIdB2AAE10AEBVPlayerB3AAAA1Z, this, a); } auto getScoreboardId(std::string* str) { return SYMCALL(ScoreboardId*, MSSYM_MD5_ecded9d31b4a1c24ba985b0a377bef64, this, str); } std::vector<Objective*>* getobjects() { return SYMCALL(std::vector<Objective*>*, MSSYM_B1QE13getObjectivesB1AE10ScoreboardB2AAA4QEBAB1QA2AVB2QDA6vectorB1AE13PEBVObjectiveB2AAA1VB2QDA9allocatorB1AE13PEBVObjectiveB3AAAA3stdB3AAAA3stdB2AAA2XZ, this); } auto getDisplayInfoFiltered(std::string* str) { return SYMCALL(std::vector<PlayerScore>*, MSSYM_MD5_3b3c17fbee13a54836ae12d93bb0dbae, this, str); } auto gettrackedscoreID() { return SYMCALL(std::vector<ScoreboardId>*, MSSYM_B1QE13getTrackedIdsB1AE10ScoreboardB2AAA4QEBAB1QA2AVB2QDA6vectorB1AE13UScoreboardIdB2AAA1VB2QDA9allocatorB1AE13UScoreboardIdB3AAAA3stdB3AAAA3stdB2AAA2XZ, this); } auto getIdentityDictionary() { return (IdentityDictionary*)((char*)this + 80);//gouzaohanshu } auto getScoreboardID(Player* a2) { return SYMCALL(PlayerScoreboardId*, MSSYM_B1QE15getScoreboardIdB1AE10ScoreboardB2AAE20QEBAAEBUScoreboardIdB2AAA9AEBVActorB3AAAA1Z, this, a2); } auto getScoreboardID2(void* a2) { return SYMCALL(ScoreboardId*, MSSYM_B1QE15getScoreboardIdB1AE10ScoreboardB2AAE20QEBAAEBUScoreboardIdB2AAA9AEBVActorB3AAAA1Z, this, a2); } auto getScoreboardIdentityRef(ScoreboardId* a2) { return SYMCALL(ScoreboardIdentityRef*, MSSYM_B1QE24getScoreboardIdentityRefB1AE10ScoreboardB2AAE29QEAAPEAVScoreboardIdentityRefB2AAE16AEBUScoreboardIdB3AAAA1Z, this, a2); } //bool请设置为1; a6=0 set,a6=1,add,a6=2,remove int modifyPlayerScore(ScoreboardId* a3, Objective* a4, int count) { bool a2 = true; return SYMCALL(int, MSSYM_B1QE17modifyPlayerScoreB1AE10ScoreboardB2AAA8QEAAHAEAB1UE17NAEBUScoreboardIdB2AAE13AEAVObjectiveB2AAE25HW4PlayerScoreSetFunctionB3AAAA1Z, this, &a2, a3, a4, count, 0); } }; #endif
4,683
C++
.h
112
38.160714
212
0.728201
zhkj-liuxiaohua/BDSNetRunner
37
8
0
LGPL-2.1
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,727
SimpleForm.h
zhkj-liuxiaohua_BDSNetRunner/BDSNetRunner/GUI/SimpleForm.h
#pragma once #include <string> #include <vector> // 创建一个简易表单字符串 extern std::string createSimpleFormString(std::string, std::string, Json::Value&); // 创建一个固定模板表单字符串 extern std::string createModalFormString(std::string, std::string, std::string, std::string);
295
C++
.h
7
35.857143
94
0.75969
zhkj-liuxiaohua/BDSNetRunner
37
8
0
LGPL-2.1
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,728
config.h
Callwater_Beerkeg-load-cell/mqtt_beer_load_cell_Sensor/config.h
// Wifi Settings #define SSID "SSID" #define PASSWORD "password" // MQTT Settings #define HOSTNAME "beer_1" #define MQTT_SERVER "server_ip" #define STATE_TOPIC "beer_1" #define STATE_RAW_TOPIC "beer_1/raw" #define AVAILABILITY_TOPIC "beer_1/available" #define TARE_TOPIC "beer_1/tare" #define TEMPERATURE_TOPIC "beer_1/temperature" #define HUMIDITY_TOPIC "beer_1/humidity" #define mqtt_username "mqtt" #define mqtt_password "password" // HX711 Pins const int LOADCELL_DOUT_PIN = 2; // Remember these are ESP GPIO pins, they are not the physical pins on the board. const int LOADCELL_SCK_PIN = 0; int calibration_factor = -22500; // Defines calibration factor we'll use for calibrating. int offset_factor = -137202; // Defines offset factor if you have static weight on the loadcell. For exaple the wight of a empty Cornelius keg. // DHT Settings constexpr auto DHT_PIN = 4; // Remember these are ESP GPIO pins, they are not the physical pins on the board. #define DHT_TYPE DHT22 // DHT11 or DHT22 constexpr auto sendDHTDataDelay = 500ul; // Delay between sending data over MQTT
1,352
C++
.h
23
56.347826
151
0.618471
Callwater/Beerkeg-load-cell
37
9
0
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,729
popsift.cpp
OpenDroneMap_pypopsift/src/popsift.cpp
#include "popsift.h" #include <algorithm> #include <cmath> #include <mutex> namespace pps{ PopSiftContext *ctx = nullptr; std::mutex g_mutex; PopSiftContext::PopSiftContext() : ps(nullptr){ popsift::cuda::device_prop_t deviceInfo; deviceInfo.set(0, false); } PopSiftContext::~PopSiftContext(){ ps->uninit(); delete ps; ps = nullptr; } void PopSiftContext::setup(float peak_threshold, float edge_threshold, bool use_root, float downsampling){ bool changed = false; if (this->peak_threshold != peak_threshold) { this->peak_threshold = peak_threshold; changed = true; } if (this->edge_threshold != edge_threshold) { this->edge_threshold = edge_threshold; changed = true; } if (this->use_root != use_root) { this->use_root = use_root; changed = true; } if (this->downsampling != downsampling) { this->downsampling = downsampling; changed = true; } if (changed){ config.setThreshold(peak_threshold); config.setEdgeLimit(edge_threshold); config.setNormMode(use_root ? popsift::Config::RootSift : popsift::Config::Classic ); config.setFilterSorting(popsift::Config::LargestScaleFirst); config.setMode(popsift::Config::OpenCV); config.setDownsampling(downsampling); // config.setOctaves(4); // config.setLevels(3); if (!ps){ ps = new PopSift(config, popsift::Config::ProcessingMode::ExtractingMode, PopSift::ByteImages ); }else{ ps->configure(config, false); } } } PopSift *PopSiftContext::get(){ return ps; } py::object popsift(pyarray_uint8 image, float peak_threshold, float edge_threshold, int target_num_features, bool use_root, float downsampling) { py::gil_scoped_release release; if (!image.size()) return py::none(); if (!ctx) ctx = new PopSiftContext(); int width = image.shape(1); int height = image.shape(0); int numFeatures = 0; while(true){ g_mutex.lock(); ctx->setup(peak_threshold, edge_threshold, use_root, downsampling); std::unique_ptr<SiftJob> job(ctx->get()->enqueue( width, height, image.data() )); std::unique_ptr<popsift::Features> result(job->get()); g_mutex.unlock(); numFeatures = result->getFeatureCount(); if (numFeatures >= target_num_features || peak_threshold < 0.0001){ popsift::Feature* feature_list = result->getFeatures(); std::vector<float> points(4 * numFeatures); std::vector<float> desc(128 * numFeatures); for (size_t i = 0; i < numFeatures; i++){ popsift::Feature pFeat = feature_list[i]; for(int oriIdx = 0; oriIdx < pFeat.num_ori; oriIdx++){ const popsift::Descriptor* pDesc = pFeat.desc[oriIdx]; for (int k = 0; k < 128; k++){ desc[128 * i + k] = pDesc->features[k]; } points[4 * i + 0] = std::min<float>(std::round(pFeat.xpos), width - 1); points[4 * i + 1] = std::min<float>(std::round(pFeat.ypos), height - 1); points[4 * i + 2] = pFeat.sigma; points[4 * i + 3] = pFeat.orientation[oriIdx]; } } py::list retn; retn.append(py_array_from_data(&points[0], numFeatures, 4)); retn.append(py_array_from_data(&desc[0], numFeatures, 128)); return retn; }else{ // Lower peak threshold if we don't meet the target peak_threshold = (peak_threshold * 2.0) / 3.0; } } // We should never get here return py::none(); } }
3,823
C++
.cpp
92
32.108696
106
0.583536
OpenDroneMap/pypopsift
37
12
5
MPL-2.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,730
main.cpp
OpenDroneMap_pypopsift/src/main.cpp
#include <pybind11/pybind11.h> #include "popsift.h" namespace py = pybind11; PYBIND11_MODULE(pypopsift, m) { m.doc() = R"pbdoc( pypopsift: Python module for CUDA accelerated GPU SIFT ----------------------- .. currentmodule:: pypopsift .. autosummary:: :toctree: _generate popsift )pbdoc"; m.def("popsift", pps::popsift, py::arg("image"), py::arg("peak_threshold") = 0.1, py::arg("edge_threshold") = 10, py::arg("target_num_features") = 4000, py::arg("use_root") = true, py::arg("downsampling") = -1 ); #ifdef VERSION_INFO m.attr("__version__") = VERSION_INFO; #else m.attr("__version__") = "dev"; #endif }
741
C++
.cpp
26
22.346154
63
0.553672
OpenDroneMap/pypopsift
37
12
5
MPL-2.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,731
popsift.h
OpenDroneMap_pypopsift/src/popsift.h
#include <pybind11/pybind11.h> #include <pybind11/numpy.h> #include <popsift/popsift.h> #include <popsift/features.h> #include <popsift/sift_conf.h> #include <popsift/sift_config.h> #include <popsift/version.hpp> #include <popsift/common/device_prop.h> #include <vector> namespace py = pybind11; namespace pps{ typedef py::array_t<float, py::array::c_style | py::array::forcecast> pyarray_f; typedef py::array_t<double, py::array::c_style | py::array::forcecast> pyarray_d; typedef py::array_t<int, py::array::c_style | py::array::forcecast> pyarray_int; typedef py::array_t<unsigned char, py::array::c_style | py::array::forcecast> pyarray_uint8; template <typename T> py::array_t<T> py_array_from_data(const T *data, size_t shape0) { py::array_t<T> res({shape0}); std::copy(data, data + shape0, res.mutable_data()); return res; } template <typename T> py::array_t<T> py_array_from_data(const T *data, size_t shape0, size_t shape1) { py::array_t<T> res({shape0, shape1}); std::copy(data, data + shape0 * shape1, res.mutable_data()); return res; } template <typename T> py::array_t<T> py_array_from_data(const T *data, size_t shape0, size_t shape1, size_t shape2) { py::array_t<T> res({shape0, shape1, shape2}); std::copy(data, data + shape0 * shape1 * shape2, res.mutable_data()); return res; } class PopSiftContext{ PopSift *ps; popsift::Config config; float peak_threshold = 0; float edge_threshold = 0; bool use_root = true; float downsampling = 0; public: PopSiftContext(); ~PopSiftContext(); void setup(float peak_threshold, float edge_threshold, bool use_root, float downsampling); PopSift *get(); }; py::object popsift(pyarray_uint8 image, float peak_threshold, float edge_threshold, int target_num_features, bool use_root, float downsampling); }
1,959
C++
.h
56
30.339286
95
0.671429
OpenDroneMap/pypopsift
37
12
5
MPL-2.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,733
CompilerContext.cpp
ethereum-optimism_solidity/libsolidity/codegen/CompilerContext.cpp
/* This file is part of solidity. solidity 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. solidity 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 solidity. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Christian <c@ethdev.com> * @date 2014 * Utilities for the solidity compiler. */ #include <libsolidity/codegen/CompilerContext.h> #include <libsolidity/ast/AST.h> #include <libsolidity/codegen/Compiler.h> #include <libsolidity/codegen/CompilerUtils.h> #include <libsolidity/interface/Version.h> #include <libyul/AsmParser.h> #include <libyul/AsmAnalysis.h> #include <libyul/AsmAnalysisInfo.h> #include <libyul/backends/evm/AsmCodeGen.h> #include <libyul/backends/evm/EVMDialect.h> #include <libyul/backends/evm/EVMMetrics.h> #include <libyul/optimiser/Suite.h> #include <libyul/Object.h> #include <libyul/YulString.h> #include <libdevcore/Whiskers.h> #include <liblangutil/ErrorReporter.h> #include <liblangutil/Scanner.h> #include <liblangutil/SourceReferenceFormatter.h> #include <boost/algorithm/string/replace.hpp> #include <utility> #include <numeric> // Change to "define" to output all intermediate code #undef SOL_OUTPUT_ASM #ifdef SOL_OUTPUT_ASM #include <libyul/AsmPrinter.h> #endif using namespace std; using namespace langutil; using namespace dev::eth; using namespace dev; using namespace dev::solidity; void CompilerContext::complexRewrite(string function, int _in, int _out, string code, vector<string> const& _localVariables, bool optimize=true) { auto methodId = FixedHash<4>(dev::keccak256(function)).hex(); auto asm_code = Whiskers(R"({ let methodId := 0x<methodId> let callBytes := msize() // replace the first 4 bytes with the right methodID mstore(callBytes, shl(224, methodId)) )")("methodId", methodId).render(); //cerr << "rewriting " << function << endl; for (int i = 0; i < _out-_in; i++) { // add padding to the stack, the value doesn't matter assemblyPtr()->append(Instruction::GAS); } if (optimize) { callLowLevelFunction(function, 0, 0, [asm_code, code, _localVariables](CompilerContext& _context) { vector<string> lv = _localVariables; lv.push_back("ret"); _context.m_disable_rewrite = true; _context.appendInlineAssembly(asm_code+code, lv); _context.m_disable_rewrite = false; } ); } else { appendInlineAssembly(asm_code+code, _localVariables); } for (int i = 0; i < _in-_out; i++) { assemblyPtr()->append(Instruction::POP); } } void CompilerContext::simpleRewrite(string function, int _in, int _out, bool optimize=true) { assert(_in <= 2); assert(_out <= 1); auto asm_code = Whiskers(R"( <input1> <input2> // overwrite call params kall(callBytes, <in_size>, callBytes, <out_size>) <output> // overwrite the memory we used back to zero so that it does not mess with downstream use of memory (e.g. bytes memory) // need to make larger than 0x40 if we ever use this for inputs exceeding 32*2 bytes in length for { let ptr := 0 } lt(ptr, 0x40) { ptr := add(ptr, 0x20) } { mstore(add(callBytes, ptr), 0) } })"); asm_code("in_size", to_string(_in*0x20+4)); asm_code("out_size", to_string(_out*0x20)); asm_code("input1", (_in >= 1) ? "mstore(add(callBytes, 4), x1)" : ""); asm_code("input2", (_in >= 2) ? "mstore(add(callBytes, 0x24), x2)" : ""); asm_code("output", (_out > 0) ? "x1 := mload(callBytes)" : ""); complexRewrite(function, _in, _out, asm_code.render(), {"x2", "x1"}, optimize); } bool CompilerContext::appendCallback(eth::AssemblyItem const& _i) { if (m_disable_rewrite) return false; m_disable_rewrite = true; auto callYUL = R"( // declare helper functions function max(first, second) -> bigger { bigger := first if gt(second, first) { bigger := second } } function min(first, second) -> smaller { smaller := first if lt(second, first) { smaller := second } } // store _gasLimit mstore(add(callBytes, 0x04), in_gas) // store _address mstore(add(callBytes, 0x24), addr) // store abi byte memory offset mstore(add(callBytes, 0x44), 0x60) // store bytes memory _calldata.length mstore(add(callBytes, 0x64), argsLength) // store bytes memory _calldata raw data let rawCallBytes := add(callBytes, 0x84) for { let ptr := 0 } lt(ptr, argsLength) { ptr := add(ptr, 0x20) } { mstore(add(rawCallBytes, ptr), mload(add(argsOffset, ptr))) } // kall, only grabbing 3 words of returndata (success & abi encoding params) and just throw on top of where we put it (successfull kall will awlays return >= 0x60 bytes) // overpad calldata by a word (argsLen [raw data] + 0x84 [abi prefixing] + 0x20 [1 word max to pad] = argsLen + 0xa4) to ensure sufficient right 0-padding for abi encoding kall(callBytes, add(0xa4, argsLength), callBytes, 0x60) // get _success let wasSuccess := mload(callBytes) // get abi length of _data output by EM let returnedDataLengthFromABI := mload(add(callBytes, 0x40)) // call identity precompile with ALL raw returndata (ignores bool and abi) to make returndatasize() correct. // also copies the relevant data back to the CALL's intended vals (retOffset, retLength) returndatacopy(callBytes, 0, returndatasize()) kopy(add(callBytes, 0x60), returnedDataLengthFromABI, retOffset, retLength) // remove all the stuff we did at callbytes let newMemSize := msize() // overwrite zeros starting from either the pre-modification msize, or the end of returndata (whichever is bigger) let endOfReturnData := add(retOffset,min(returndatasize(), retLength)) for { let ptr := max(callBytes, endOfReturnData) } lt(ptr, newMemSize) { ptr := add(ptr, 0x20) } { mstore(ptr, 0x00) } // set the first stack element out, this looks weird but it's really saying this is the intended stack output of the replaced EVM operation retLength := wasSuccess })"; if (_i.type() == PushData) { auto dat = assemblyPtr()->data(_i.data()); if (std::find(dat.begin(), dat.end(), 0x5b) != dat.end()) { m_errorReporter.warning( assemblyPtr()->getSourceLocation(), "OVM: JUMPDEST found in constant"); } } bool ret = false; if (_i.type() == Operation) { ret = true; // will be set to false again if we don't change the instruction switch (_i.instruction()) { case Instruction::SELFBALANCE: case Instruction::BALANCE: m_errorReporter.parserError( assemblyPtr()->getSourceLocation(), "OVM: " + instructionInfo(_i.instruction()).name + " is not implemented in the OVM. (We have no native ETH -- use deposited WETH instead!)" ); ret = false; break; case Instruction::BLOCKHASH: case Instruction::CALLCODE: case Instruction::COINBASE: case Instruction::DIFFICULTY: case Instruction::GASPRICE: case Instruction::ORIGIN: case Instruction::SELFDESTRUCT: m_errorReporter.parserError( assemblyPtr()->getSourceLocation(), "OVM: " + instructionInfo(_i.instruction()).name + " is not implemented in the OVM." ); ret = false; break; case Instruction::ADDRESS: // address doesn't like to be optimized for some reason // a very small price to pay simpleRewrite("ovmADDRESS()", 0, 1, false); break; case Instruction::CALLER: simpleRewrite("ovmCALLER()", 0, 1); break; case Instruction::CHAINID: simpleRewrite("ovmCHAINID()", 0, 1); break; case Instruction::EXTCODESIZE: simpleRewrite("ovmEXTCODESIZE(address)", 1, 1); break; case Instruction::EXTCODEHASH: simpleRewrite("ovmEXTCODEHASH(address)", 1, 1); break; case Instruction::GASLIMIT: simpleRewrite("ovmGASLIMIT()", 0, 1); break; case Instruction::NUMBER: simpleRewrite("ovmNUMBER()", 0, 1); break; case Instruction::SSTORE: simpleRewrite("ovmSSTORE(bytes32,bytes32)", 2, 0); break; case Instruction::SLOAD: simpleRewrite("ovmSLOAD(bytes32)", 1, 1); break; case Instruction::TIMESTAMP: simpleRewrite("ovmTIMESTAMP()", 0, 1); break; case Instruction::CALL: complexRewrite("ovmCALL(uint256,address,bytes)", 7, 1, callYUL, {"retLength", "retOffset", "argsLength", "argsOffset", "value", "addr", "in_gas"}); break; case Instruction::STATICCALL: complexRewrite("ovmSTATICCALL(uint256,address,bytes)", 6, 1, callYUL, {"retLength", "retOffset", "argsLength", "argsOffset", "addr", "in_gas"}); break; case Instruction::DELEGATECALL: complexRewrite("ovmDELEGATECALL(uint256,address,bytes)", 6, 1, callYUL, {"retLength", "retOffset", "argsLength", "argsOffset", "addr", "in_gas"}); break; case Instruction::REVERT: complexRewrite("ovmREVERT(bytes)", 2, 0, R"( // methodId is stored for us at callBytes let dataStart := add(callBytes, 4) // store abi offset mstore(dataStart, 0x20) // store abi length mstore(add(dataStart, 0x20), length) // store bytecode itself for { let ptr := 0 } lt(ptr, length) { ptr := add(ptr, 0x20) } { mstore(add(add(dataStart, 0x40), ptr), mload(add(offset, ptr))) } // technically 0x44 is the minimum needed to add to length, but ABI wants right-padding so we overpad by 0x20. kall(callBytes, add(0x64, length), callBytes, 0x20) // kall to ovmREVERT will itself trigger safe reversion so nothing further needed! })", {"length", "offset"}); break; case Instruction::CREATE: complexRewrite("ovmCREATE(bytes)", 3, 1, R"( // methodId is stored for us at callBytes let dataStart := add(callBytes, 4) // store abi offset mstore(dataStart, 0x20) // store abi length mstore(add(dataStart, 0x20), length) // store bytecode itself for { let ptr := 0 } lt(ptr, length) { ptr := add(ptr, 0x20) } { mstore(add(add(dataStart, 0x40), ptr), mload(add(offset, ptr))) } // technically 0x44 is the minimum needed to add to length, but ABI wants right-padding so we overpad by 0x20. kall(callBytes, add(0x64, length), callBytes, 0x20) // length is first stack val in ==> first stack val out (address) length := mload(callBytes) // remove all the stuff we did at callbytes. let newMemSize := msize() for { let ptr := callBytes } lt(ptr, newMemSize) { ptr := add(ptr, 0x20) } { mstore(ptr, 0x00) } })", {"length", "offset", "value"}); break; case Instruction::CREATE2: complexRewrite("ovmCREATE2(bytes,bytes32)", 4, 1, R"( // methodId is stored for us at callBytes let dataStart := add(callBytes, 4) // store abi offset mstore(dataStart, 0x40) // store salt mstore(add(dataStart, 0x20), salt) // store abi length mstore(add(dataStart, 0x40), length) // store bytecode itself for { let ptr := 0 } lt(ptr, length) { ptr := add(ptr, 0x20) } { mstore(add(add(dataStart, 0x60), ptr), mload(add(offset, ptr))) } // technically 0x64 is the minimum needed to add to length, but ABI wants right-padding so we overpad by 0x20. kall(callBytes, add(0x84, length), callBytes, 0x20) // salt is first stack val in ==> first stack val out (address) salt := mload(callBytes) // remove all the stuff we did at callbytes. let newMemSize := msize() for { let ptr := callBytes } lt(ptr, newMemSize) { ptr := add(ptr, 0x20) } { mstore(callBytes, 0x00) } })", {"salt", "length", "offset", "value"}); break; case Instruction::EXTCODECOPY: complexRewrite("ovmEXTCODECOPY(address,uint256,uint256)", 4, 0, R"( mstore(add(callBytes, 4), addr) mstore(add(callBytes, 0x24), offset) mstore(add(callBytes, 0x44), length) kall(callBytes, 0x64, destOffset, length) // remove all the stuff we did at callbytes, except for any part of the copied code itself which extended past callbytes. let newMemSize := msize() for { let ptr := max(callBytes, add(destOffset, length)) } lt(ptr, newMemSize) { ptr := add(ptr, 0x20) } { mstore(ptr, 0x00) } })", {"length", "offset", "destOffset", "addr"}); break; case Instruction::RETURNDATACOPY: case Instruction::RETURNDATASIZE: if (m_is_building_user_asm) { m_errorReporter.warning( assemblyPtr()->getSourceLocation(), "OVM: Using RETURNDATASIZE or RETURNDATACOPY in user asm isn't guaranteed to work"); } ret = false; break; default: ret = false; break; } } m_disable_rewrite = false; return ret; } void CompilerContext::addStateVariable( VariableDeclaration const& _declaration, u256 const& _storageOffset, unsigned _byteOffset ) { m_stateVariables[&_declaration] = make_pair(_storageOffset, _byteOffset); } void CompilerContext::startFunction(Declaration const& _function) { m_functionCompilationQueue.startFunction(_function); *this << functionEntryLabel(_function); } void CompilerContext::callLowLevelFunction( string const& _name, unsigned _inArgs, unsigned _outArgs, function<void(CompilerContext&)> const& _generator ) { eth::AssemblyItem retTag = pushNewTag(); CompilerUtils(*this).moveIntoStack(_inArgs); *this << lowLevelFunctionTag(_name, _inArgs, _outArgs, _generator); appendJump(eth::AssemblyItem::JumpType::IntoFunction); adjustStackOffset(int(_outArgs) - 1 - _inArgs); *this << retTag.tag(); } eth::AssemblyItem CompilerContext::lowLevelFunctionTag( string const& _name, unsigned _inArgs, unsigned _outArgs, function<void(CompilerContext&)> const& _generator ) { auto it = m_lowLevelFunctions.find(_name); if (it == m_lowLevelFunctions.end()) { eth::AssemblyItem tag = newTag().pushTag(); m_lowLevelFunctions.insert(make_pair(_name, tag)); m_lowLevelFunctionGenerationQueue.push(make_tuple(_name, _inArgs, _outArgs, _generator)); return tag; } else return it->second; } void CompilerContext::appendMissingLowLevelFunctions() { while (!m_lowLevelFunctionGenerationQueue.empty()) { string name; unsigned inArgs; unsigned outArgs; function<void(CompilerContext&)> generator; tie(name, inArgs, outArgs, generator) = m_lowLevelFunctionGenerationQueue.front(); m_lowLevelFunctionGenerationQueue.pop(); setStackOffset(inArgs + 1); *this << m_lowLevelFunctions.at(name).tag(); generator(*this); CompilerUtils(*this).moveToStackTop(outArgs); appendJump(eth::AssemblyItem::JumpType::OutOfFunction); solAssert(stackHeight() == outArgs, "Invalid stack height in low-level function " + name + "."); } } void CompilerContext::addVariable( VariableDeclaration const& _declaration, unsigned _offsetToCurrent ) { solAssert(m_asm->deposit() >= 0 && unsigned(m_asm->deposit()) >= _offsetToCurrent, ""); unsigned sizeOnStack = _declaration.annotation().type->sizeOnStack(); // Variables should not have stack size other than [1, 2], // but that might change when new types are introduced. solAssert(sizeOnStack == 1 || sizeOnStack == 2, ""); m_localVariables[&_declaration].push_back(unsigned(m_asm->deposit()) - _offsetToCurrent); } void CompilerContext::removeVariable(Declaration const& _declaration) { solAssert(m_localVariables.count(&_declaration) && !m_localVariables[&_declaration].empty(), ""); m_localVariables[&_declaration].pop_back(); if (m_localVariables[&_declaration].empty()) m_localVariables.erase(&_declaration); } void CompilerContext::removeVariablesAboveStackHeight(unsigned _stackHeight) { vector<Declaration const*> toRemove; for (auto _var: m_localVariables) { solAssert(!_var.second.empty(), ""); solAssert(_var.second.back() <= stackHeight(), ""); if (_var.second.back() >= _stackHeight) toRemove.push_back(_var.first); } for (auto _var: toRemove) removeVariable(*_var); } unsigned CompilerContext::numberOfLocalVariables() const { return m_localVariables.size(); } shared_ptr<eth::Assembly> CompilerContext::compiledContract(ContractDefinition const& _contract) const { auto ret = m_otherCompilers.find(&_contract); solAssert(ret != m_otherCompilers.end(), "Compiled contract not found."); return ret->second->assemblyPtr(); } shared_ptr<eth::Assembly> CompilerContext::compiledContractRuntime(ContractDefinition const& _contract) const { auto ret = m_otherCompilers.find(&_contract); solAssert(ret != m_otherCompilers.end(), "Compiled contract not found."); return ret->second->runtimeAssemblyPtr(); } bool CompilerContext::isLocalVariable(Declaration const* _declaration) const { return !!m_localVariables.count(_declaration); } eth::AssemblyItem CompilerContext::functionEntryLabel(Declaration const& _declaration) { return m_functionCompilationQueue.entryLabel(_declaration, *this); } eth::AssemblyItem CompilerContext::functionEntryLabelIfExists(Declaration const& _declaration) const { return m_functionCompilationQueue.entryLabelIfExists(_declaration); } FunctionDefinition const& CompilerContext::resolveVirtualFunction(FunctionDefinition const& _function) { // Libraries do not allow inheritance and their functions can be inlined, so we should not // search the inheritance hierarchy (which will be the wrong one in case the function // is inlined). if (auto scope = dynamic_cast<ContractDefinition const*>(_function.scope())) if (scope->isLibrary()) return _function; solAssert(!m_inheritanceHierarchy.empty(), "No inheritance hierarchy set."); return resolveVirtualFunction(_function, m_inheritanceHierarchy.begin()); } FunctionDefinition const& CompilerContext::superFunction(FunctionDefinition const& _function, ContractDefinition const& _base) { solAssert(!m_inheritanceHierarchy.empty(), "No inheritance hierarchy set."); return resolveVirtualFunction(_function, superContract(_base)); } FunctionDefinition const* CompilerContext::nextConstructor(ContractDefinition const& _contract) const { vector<ContractDefinition const*>::const_iterator it = superContract(_contract); for (; it != m_inheritanceHierarchy.end(); ++it) if ((*it)->constructor()) return (*it)->constructor(); return nullptr; } Declaration const* CompilerContext::nextFunctionToCompile() const { return m_functionCompilationQueue.nextFunctionToCompile(); } ModifierDefinition const& CompilerContext::resolveVirtualFunctionModifier( ModifierDefinition const& _modifier ) const { // Libraries do not allow inheritance and their functions can be inlined, so we should not // search the inheritance hierarchy (which will be the wrong one in case the function // is inlined). if (auto scope = dynamic_cast<ContractDefinition const*>(_modifier.scope())) if (scope->isLibrary()) return _modifier; solAssert(!m_inheritanceHierarchy.empty(), "No inheritance hierarchy set."); for (ContractDefinition const* contract: m_inheritanceHierarchy) for (ModifierDefinition const* modifier: contract->functionModifiers()) if (modifier->name() == _modifier.name()) return *modifier; solAssert(false, "Function modifier " + _modifier.name() + " not found in inheritance hierarchy."); } unsigned CompilerContext::baseStackOffsetOfVariable(Declaration const& _declaration) const { auto res = m_localVariables.find(&_declaration); solAssert(res != m_localVariables.end(), "Variable not found on stack."); solAssert(!res->second.empty(), ""); return res->second.back(); } unsigned CompilerContext::baseToCurrentStackOffset(unsigned _baseOffset) const { return m_asm->deposit() - _baseOffset - 1; } unsigned CompilerContext::currentToBaseStackOffset(unsigned _offset) const { return m_asm->deposit() - _offset - 1; } pair<u256, unsigned> CompilerContext::storageLocationOfVariable(Declaration const& _declaration) const { auto it = m_stateVariables.find(&_declaration); solAssert(it != m_stateVariables.end(), "Variable not found in storage."); return it->second; } CompilerContext& CompilerContext::appendJump(eth::AssemblyItem::JumpType _jumpType) { eth::AssemblyItem item(Instruction::JUMP); item.setJumpType(_jumpType); return *this << item; } CompilerContext& CompilerContext::appendInvalid() { return *this << Instruction::INVALID; } CompilerContext& CompilerContext::appendConditionalInvalid() { *this << Instruction::ISZERO; eth::AssemblyItem afterTag = appendConditionalJump(); *this << Instruction::INVALID; *this << afterTag; return *this; } CompilerContext& CompilerContext::appendRevert() { return *this << u256(0) << u256(0) << Instruction::REVERT; } CompilerContext& CompilerContext::appendConditionalRevert(bool _forwardReturnData) { if (_forwardReturnData && m_evmVersion.supportsReturndata()) appendInlineAssembly(R"({ if condition { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } })", {"condition"}); else appendInlineAssembly(R"({ if condition { revert(0, 0) } })", {"condition"}); *this << Instruction::POP; return *this; } void CompilerContext::resetVisitedNodes(ASTNode const* _node) { stack<ASTNode const*> newStack; newStack.push(_node); std::swap(m_visitedNodes, newStack); updateSourceLocation(); } void CompilerContext::appendInlineAssembly( string const& _assembly, vector<string> const& _localVariables, set<string> const& _externallyUsedFunctions, bool _system, OptimiserSettings const& _optimiserSettings ) { int startStackHeight = stackHeight(); set<yul::YulString> externallyUsedIdentifiers; for (auto const& fun: _externallyUsedFunctions) externallyUsedIdentifiers.insert(yul::YulString(fun)); for (auto const& var: _localVariables) externallyUsedIdentifiers.insert(yul::YulString(var)); yul::ExternalIdentifierAccess identifierAccess; identifierAccess.resolve = [&]( yul::Identifier const& _identifier, yul::IdentifierContext, bool _insideFunction ) -> size_t { if (_insideFunction) return size_t(-1); auto it = std::find(_localVariables.begin(), _localVariables.end(), _identifier.name.str()); return it == _localVariables.end() ? size_t(-1) : 1; }; identifierAccess.generateCode = [&]( yul::Identifier const& _identifier, yul::IdentifierContext _context, yul::AbstractAssembly& _assembly ) { auto it = std::find(_localVariables.begin(), _localVariables.end(), _identifier.name.str()); solAssert(it != _localVariables.end(), ""); int stackDepth = _localVariables.end() - it; int stackDiff = _assembly.stackHeight() - startStackHeight + stackDepth; if (_context == yul::IdentifierContext::LValue) stackDiff -= 1; if (stackDiff < 1 || stackDiff > 16) BOOST_THROW_EXCEPTION( CompilerError() << errinfo_sourceLocation(_identifier.location) << errinfo_comment("Stack too deep (" + to_string(stackDiff) + "), try removing local variables.") ); if (_context == yul::IdentifierContext::RValue) _assembly.appendInstruction(dupInstruction(stackDiff)); else { _assembly.appendInstruction(swapInstruction(stackDiff)); _assembly.appendInstruction(Instruction::POP); } }; ErrorList errors; ErrorReporter errorReporter(errors); auto scanner = make_shared<langutil::Scanner>(langutil::CharStream(_assembly, "--CODEGEN--")); yul::EVMDialect const& dialect = yul::EVMDialect::strictAssemblyForEVM(m_evmVersion); auto parserResult = yul::Parser(errorReporter, dialect).parse(scanner, false); #ifdef SOL_OUTPUT_ASM cout << yul::AsmPrinter()(*parserResult) << endl; #endif auto reportError = [&](string const& _context) { string message = "Error parsing/analyzing inline assembly block:\n" + _context + "\n" "------------------ Input: -----------------\n" + _assembly + "\n" "------------------ Errors: ----------------\n"; for (auto const& error: errorReporter.errors()) message += SourceReferenceFormatter::formatErrorInformation(*error); message += "-------------------------------------------\n"; solAssert(false, message); }; yul::AsmAnalysisInfo analysisInfo; bool analyzerResult = false; if (parserResult) analyzerResult = yul::AsmAnalyzer( analysisInfo, errorReporter, std::nullopt, dialect, identifierAccess.resolve ).analyze(*parserResult); if (!parserResult || !errorReporter.errors().empty() || !analyzerResult) reportError("Invalid assembly generated by code generator."); // Several optimizer steps cannot handle externally supplied stack variables, // so we essentially only optimize the ABI functions. if (_optimiserSettings.runYulOptimiser && _localVariables.empty()) { bool const isCreation = m_runtimeContext != nullptr; yul::GasMeter meter(dialect, isCreation, _optimiserSettings.expectedExecutionsPerDeployment); yul::Object obj; obj.code = parserResult; obj.analysisInfo = make_shared<yul::AsmAnalysisInfo>(analysisInfo); yul::OptimiserSuite::run( dialect, &meter, obj, _optimiserSettings.optimizeStackAllocation, externallyUsedIdentifiers ); analysisInfo = std::move(*obj.analysisInfo); parserResult = std::move(obj.code); #ifdef SOL_OUTPUT_ASM cout << "After optimizer:" << endl; cout << yul::AsmPrinter()(*parserResult) << endl; #endif } if (!errorReporter.errors().empty()) reportError("Failed to analyze inline assembly block."); solAssert(errorReporter.errors().empty(), "Failed to analyze inline assembly block."); yul::CodeGenerator::assemble( *parserResult, analysisInfo, *m_asm, m_evmVersion, identifierAccess, _system, _optimiserSettings.optimizeStackAllocation ); // Reset the source location to the one of the node (instead of the CODEGEN source location) updateSourceLocation(); } FunctionDefinition const& CompilerContext::resolveVirtualFunction( FunctionDefinition const& _function, vector<ContractDefinition const*>::const_iterator _searchStart ) { string name = _function.name(); FunctionType functionType(_function); auto it = _searchStart; for (; it != m_inheritanceHierarchy.end(); ++it) for (FunctionDefinition const* function: (*it)->definedFunctions()) if ( function->name() == name && !function->isConstructor() && FunctionType(*function).asCallableFunction(false)->hasEqualParameterTypes(functionType) ) return *function; solAssert(false, "Super function " + name + " not found."); return _function; // not reached } vector<ContractDefinition const*>::const_iterator CompilerContext::superContract(ContractDefinition const& _contract) const { solAssert(!m_inheritanceHierarchy.empty(), "No inheritance hierarchy set."); auto it = find(m_inheritanceHierarchy.begin(), m_inheritanceHierarchy.end(), &_contract); solAssert(it != m_inheritanceHierarchy.end(), "Base not found in inheritance hierarchy."); return ++it; } void CompilerContext::updateSourceLocation() { m_asm->setSourceLocation(m_visitedNodes.empty() ? SourceLocation() : m_visitedNodes.top()->location()); } eth::Assembly::OptimiserSettings CompilerContext::translateOptimiserSettings(OptimiserSettings const& _settings) { // Constructing it this way so that we notice changes in the fields. eth::Assembly::OptimiserSettings asmSettings{false, false, false, false, false, false, m_evmVersion, 0}; asmSettings.isCreation = true; asmSettings.runJumpdestRemover = _settings.runJumpdestRemover; asmSettings.runPeephole = _settings.runPeephole; asmSettings.runDeduplicate = _settings.runDeduplicate; asmSettings.runCSE = _settings.runCSE; asmSettings.runConstantOptimiser = _settings.runConstantOptimiser; asmSettings.expectedExecutionsPerDeployment = _settings.expectedExecutionsPerDeployment; asmSettings.evmVersion = m_evmVersion; return asmSettings; } eth::AssemblyItem CompilerContext::FunctionCompilationQueue::entryLabel( Declaration const& _declaration, CompilerContext& _context ) { auto res = m_entryLabels.find(&_declaration); if (res == m_entryLabels.end()) { eth::AssemblyItem tag(_context.newTag()); m_entryLabels.insert(make_pair(&_declaration, tag)); m_functionsToCompile.push(&_declaration); return tag.tag(); } else return res->second.tag(); } eth::AssemblyItem CompilerContext::FunctionCompilationQueue::entryLabelIfExists(Declaration const& _declaration) const { auto res = m_entryLabels.find(&_declaration); return res == m_entryLabels.end() ? eth::AssemblyItem(eth::UndefinedItem) : res->second.tag(); } Declaration const* CompilerContext::FunctionCompilationQueue::nextFunctionToCompile() const { while (!m_functionsToCompile.empty()) { if (m_alreadyCompiledFunctions.count(m_functionsToCompile.front())) m_functionsToCompile.pop(); else return m_functionsToCompile.front(); } return nullptr; } void CompilerContext::FunctionCompilationQueue::startFunction(Declaration const& _function) { if (!m_functionsToCompile.empty() && m_functionsToCompile.front() == &_function) m_functionsToCompile.pop(); m_alreadyCompiledFunctions.insert(&_function); }
29,092
C++
.cpp
768
34.799479
173
0.729189
ethereum-optimism/solidity
36
13
10
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,739
WinMTRGlobal.cpp
leeter_WinMTR-refresh/WinMTRGlobal.cpp
/* WinMTR Copyright (C) 2010-2019 Appnor MSP S.A. - http://www.appnor.com Copyright (C) 2019-2021 Leetsoftwerx This program 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; version 2 of the License. This program 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 this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "WinMTRGlobal.h"
779
C++
.cpp
17
44.588235
79
0.80343
leeter/WinMTR-refresh
36
6
5
GPL-2.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,740
WinMTRProperties.cpp
leeter_WinMTR-refresh/WinMTRProperties.cpp
/* WinMTR Copyright (C) 2010-2019 Appnor MSP S.A. - http://www.appnor.com Copyright (C) 2019-2021 Leetsoftwerx This program 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; version 2 of the License. This program 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 this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ //***************************************************************************** // FILE: WinMTRProperties.cpp // // //***************************************************************************** #include "WinMTRGlobal.h" #include "WinMTRProperties.h" import <format>; import WinMTRUtils; #include "resource.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif //***************************************************************************** // BEGIN_MESSAGE_MAP // // //***************************************************************************** BEGIN_MESSAGE_MAP(WinMTRProperties, CDialog) END_MESSAGE_MAP() //***************************************************************************** // WinMTRProperties::WinMTRProperties // // //***************************************************************************** WinMTRProperties::WinMTRProperties(CWnd* pParent) noexcept : CDialog(WinMTRProperties::IDD, pParent) ,ping_last() ,ping_best() ,ping_avrg() ,ping_worst() ,pck_sent() ,pck_recv() ,pck_loss() { } //***************************************************************************** // WinMTRroperties::DoDataExchange // // //***************************************************************************** void WinMTRProperties::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_EDIT_PHOST, m_editHost); DDX_Control(pDX, IDC_EDIT_PIP, m_editIP); DDX_Control(pDX, IDC_EDIT_PCOMMENT, m_editComment); DDX_Control(pDX, IDC_EDIT_PLOSS, m_editLoss); DDX_Control(pDX, IDC_EDIT_PSENT, m_editSent); DDX_Control(pDX, IDC_EDIT_PRECV, m_editRecv); DDX_Control(pDX, IDC_EDIT_PLAST, m_editLast); DDX_Control(pDX, IDC_EDIT_PBEST, m_editBest); DDX_Control(pDX, IDC_EDIT_PWORST, m_editWorst); DDX_Control(pDX, IDC_EDIT_PAVRG, m_editAvrg); } //***************************************************************************** // WinMTRProperties::OnInitDialog // // //***************************************************************************** BOOL WinMTRProperties::OnInitDialog() { CDialog::OnInitDialog(); wchar_t buf[255] = {}; m_editIP.SetWindowText(ip.c_str()); m_editHost.SetWindowText(host.c_str()); m_editComment.SetWindowText(comment.c_str()); constexpr auto writable_size = std::size(buf) - 1; auto result = std::format_to_n(buf, writable_size, WinMTRUtils::int_number_format, pck_loss); *result.out = '\0'; m_editLoss.SetWindowText(buf); result = std::format_to_n(buf, writable_size, WinMTRUtils::int_number_format, pck_sent); *result.out = '\0'; m_editSent.SetWindowText(buf); result = std::format_to_n(buf, writable_size, WinMTRUtils::int_number_format, pck_recv); *result.out = '\0'; m_editRecv.SetWindowText(buf); result = std::format_to_n(buf, writable_size, WinMTRUtils::float_number_format, ping_last); *result.out = '\0'; m_editLast.SetWindowText(buf); result = std::format_to_n(buf, writable_size, WinMTRUtils::float_number_format, ping_best); *result.out = '\0'; m_editBest.SetWindowText(buf); result = std::format_to_n(buf, writable_size, WinMTRUtils::float_number_format, ping_worst); *result.out = '\0'; m_editWorst.SetWindowText(buf); result = std::format_to_n(buf, writable_size, WinMTRUtils::float_number_format, ping_avrg); *result.out = '\0'; m_editAvrg.SetWindowText(buf); return FALSE; }
4,115
C++
.cpp
108
36.481481
100
0.603916
leeter/WinMTR-refresh
36
6
5
GPL-2.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,741
WinMTRDialog-tracing.cpp
leeter_WinMTR-refresh/WinMTRDialog-tracing.cpp
/* WinMTR Copyright (C) 2010-2019 Appnor MSP S.A. - http://www.appnor.com Copyright (C) 2019-2023 Leetsoftwerx This program 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; version 2 of the License. This program 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 this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ module; #pragma warning (disable : 4005) #include "targetver.h" #define WIN32_LEAN_AND_MEAN #define NOMINMAX #include <afx.h> #include <afxext.h> #include <afxdisp.h> #include <ws2tcpip.h> #include <ws2ipdef.h> #include "resource.h" module WinMTR.Dialog:tracing; import :ClassDef; import WinMTRSNetHost; import WinMTRDnsUtil; import <stop_token>; import <optional>; import <mutex>; import <format>; import <string_view>; import <winrt/Windows.Foundation.h>; using namespace std::literals; //***************************************************************************** // WinMTRDialog::InitMTRNet // // //***************************************************************************** bool WinMTRDialog::InitMTRNet() noexcept { CString sHost; m_comboHost.GetWindowTextW(sHost); if (sHost.IsEmpty()) [[unlikely]] { // Technically never because this is caught in the calling function sHost = L"localhost"; } SOCKADDR_INET addrstore{}; for (auto af : { AF_INET, AF_INET6 }) { INT addrSize = sizeof(addrstore); if (auto res = WSAStringToAddressW( sHost.GetBuffer() , af , nullptr , reinterpret_cast<LPSOCKADDR>(&addrstore) , &addrSize); !res) { return true; } } const auto buf = std::format(L"Resolving host {}..."sv, sHost.GetString()); statusBar.SetPaneText(0, buf.c_str()); std::unique_ptr<ADDRINFOEXW, addrinfo_deleter> holder; ADDRINFOEXW hint = { .ai_family = AF_UNSPEC }; if (const auto result = GetAddrInfoExW( sHost , nullptr , NS_ALL , nullptr , &hint , std::out_ptr(holder) , nullptr , nullptr , nullptr , nullptr); result != ERROR_SUCCESS) { statusBar.SetPaneText(0, CString((LPCTSTR)IDS_STRING_SB_NAME)); AfxMessageBox(IDS_STRING_UNABLE_TO_RESOLVE_HOSTNAME); return false; } return true; } winrt::Windows::Foundation::IAsyncAction WinMTRDialog::pingThread(std::stop_token stop_token, std::wstring sHost) { if (tracing.exchange(true)) { throw new std::runtime_error("Tracing started twice!"); } struct tracexit { WinMTRDialog* dialog; ~tracexit() noexcept { dialog->tracing.store(false, std::memory_order_release); } }tracexit{ this }; SOCKADDR_INET addrstore = {}; for (auto af : { AF_INET, AF_INET6 }) { INT addrSize = sizeof(addrstore); if (auto res = WSAStringToAddressW( sHost.data() , af , nullptr , reinterpret_cast<LPSOCKADDR>(&addrstore) , &addrSize); !res) { co_await this->wmtrnet->DoTrace(stop_token, std::move(addrstore)); co_return; } } int hintFamily = AF_UNSPEC; //both if (!this->useIPv4) { hintFamily = AF_INET6; } else if (!this->useIPv6) { hintFamily = AF_INET; } timeval timeout{ .tv_sec = 30 }; auto result = co_await GetAddrInfoAsync(sHost, &timeout, hintFamily); if (!result || result->empty()) { AfxMessageBox(IDS_STRING_UNABLE_TO_RESOLVE_HOSTNAME); co_return; } addrstore = result->front(); co_await this->wmtrnet->DoTrace(stop_token, std::move(addrstore)); } winrt::fire_and_forget WinMTRDialog::stopTrace() { // grab the thread under a mutex so we don't mess this up and cause a data race decltype(trace_lacky) temp; { std::unique_lock trace_lock{ tracer_mutex }; std::swap(temp, trace_lacky); } // don't bother trying call something not there if (!temp) { co_return; } co_await winrt::resume_background(); temp.reset(); //trigger the stop token co_return; }
4,112
C++
.cpp
141
26.964539
113
0.704425
leeter/WinMTR-refresh
36
6
5
GPL-2.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,742
WinMTRDialog-StateMachine.cpp
leeter_WinMTR-refresh/WinMTRDialog-StateMachine.cpp
/* WinMTR Copyright (C) 2010-2019 Appnor MSP S.A. - http://www.appnor.com Copyright (C) 2019-2023 Leetsoftwerx This program 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; version 2 of the License. This program 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 this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ module; #pragma warning (disable : 4005) #include "targetver.h" #define WIN32_LEAN_AND_MEAN #include <afx.h> #include <afxext.h> #include <afxdisp.h> #include "resource.h" module WinMTR.Dialog:StateMachine; import :ClassDef; import <mutex>; import <string>; import <winrt/Windows.Foundation.h>; #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #ifdef DEBUG #define TRACE_MSG(msg) \ { \ std::wostringstream dbg_msg(std::wostringstream::out); \ dbg_msg << msg << std::endl; \ OutputDebugStringW(dbg_msg.str().c_str()); \ } #else #define TRACE_MSG(msg) #endif void WinMTRDialog::Transit(STATES new_state) { switch (new_state) { case STATES::IDLE: switch (state) { case STATES::STOPPING: transition = STATE_TRANSITIONS::STOPPING_TO_IDLE; break; case STATES::IDLE: transition = STATE_TRANSITIONS::IDLE_TO_IDLE; break; default: TRACE_MSG(L"Received state IDLE after " << static_cast<int>(state)); return; } state = STATES::IDLE; break; case STATES::TRACING: switch (state) { case STATES::IDLE: transition = STATE_TRANSITIONS::IDLE_TO_TRACING; break; case STATES::TRACING: transition = STATE_TRANSITIONS::TRACING_TO_TRACING; break; default: TRACE_MSG(L"Received state TRACING after " << static_cast<int>(state)); return; } state = STATES::TRACING; break; case STATES::STOPPING: switch (state) { case STATES::STOPPING: transition = STATE_TRANSITIONS::STOPPING_TO_STOPPING; break; case STATES::TRACING: transition = STATE_TRANSITIONS::TRACING_TO_STOPPING; break; default: TRACE_MSG(L"Received state STOPPING after " << static_cast<int>(state)); return; } state = STATES::STOPPING; break; case STATES::EXIT: switch (state) { case STATES::IDLE: transition = STATE_TRANSITIONS::IDLE_TO_EXIT; break; case STATES::STOPPING: transition = STATE_TRANSITIONS::STOPPING_TO_EXIT; break; case STATES::TRACING: transition = STATE_TRANSITIONS::TRACING_TO_EXIT; break; case STATES::EXIT: break; default: TRACE_MSG(L"Received state EXIT after " << static_cast<int>(state)); return; } state = STATES::EXIT; break; default: TRACE_MSG(L"Received state " << static_cast<std::underlying_type_t<STATES>>(state)); } // modify controls according to new state switch (transition) { case STATE_TRANSITIONS::IDLE_TO_TRACING: { m_buttonStart.EnableWindow(FALSE); CString newText; newText.LoadStringW(IDS_STRING_STOP); m_buttonStart.SetWindowText(newText); m_comboHost.EnableWindow(FALSE); m_buttonOptions.EnableWindow(FALSE); newText.LoadStringW(IDS_STRING_DBL_CLICK_MORE_INFO); statusBar.SetPaneText(0, newText); // using a different thread to create an MTA so we don't have explosion issues with the // thread pool CString sHost; this->m_comboHost.GetWindowTextW(sHost); if (sHost.IsEmpty()) [[unlikely]] { // Technically never because this is caught in the calling function sHost = L"localhost"; } std::unique_lock trace_lock{ tracer_mutex }; // create the jthread and stop token all in one go trace_lacky.emplace([this](std::stop_token stop_token, auto sHost) noexcept { winrt::init_apartment(winrt::apartment_type::multi_threaded); try { auto tracer_local = this->pingThread(stop_token, sHost); { std::unique_lock lock(this->tracer_mutex); } // keep the thread alive tracer_local.get(); } catch (winrt::hresult_canceled const&) { // don't care this happens } catch (winrt::hresult_illegal_method_call const&) { // don't care this happens } }, std::wstring(sHost)); } m_buttonStart.EnableWindow(TRUE); break; case STATE_TRANSITIONS::IDLE_TO_IDLE: // nothing to be done break; case STATE_TRANSITIONS::STOPPING_TO_IDLE: { CString newText; newText.LoadStringW(IDS_STRING_START); m_buttonStart.EnableWindow(TRUE); statusBar.SetPaneText(0, CString((LPCSTR)IDS_STRING_SB_NAME)); m_buttonStart.SetWindowText(newText); m_comboHost.EnableWindow(TRUE); m_buttonOptions.EnableWindow(TRUE); m_comboHost.SetFocus(); } break; case STATE_TRANSITIONS::STOPPING_TO_STOPPING: DisplayRedraw(); break; case STATE_TRANSITIONS::TRACING_TO_TRACING: DisplayRedraw(); break; case STATE_TRANSITIONS::TRACING_TO_STOPPING: { m_buttonStart.EnableWindow(FALSE); m_comboHost.EnableWindow(FALSE); m_buttonOptions.EnableWindow(FALSE); this->stopTrace(); CString newText; newText.LoadStringW(IDS_STRING_WAITING_STOP_TRACE); statusBar.SetPaneText(0, newText); DisplayRedraw(); } break; case STATE_TRANSITIONS::IDLE_TO_EXIT: m_buttonStart.EnableWindow(FALSE); m_comboHost.EnableWindow(FALSE); m_buttonOptions.EnableWindow(FALSE); break; case STATE_TRANSITIONS::TRACING_TO_EXIT: { m_buttonStart.EnableWindow(FALSE); m_comboHost.EnableWindow(FALSE); m_buttonOptions.EnableWindow(FALSE); this->stopTrace(); CString newText; newText.LoadStringW(IDS_STRING_WAITING_STOP_TRACE); statusBar.SetPaneText(0, newText); } break; case STATE_TRANSITIONS::STOPPING_TO_EXIT: m_buttonStart.EnableWindow(FALSE); m_comboHost.EnableWindow(FALSE); m_buttonOptions.EnableWindow(FALSE); break; default: TRACE_MSG("Unknown transition " << static_cast<std::underlying_type_t<STATE_TRANSITIONS>>(transition)); break; } } void WinMTRDialog::OnTimer(UINT_PTR nIDEvent) noexcept { static unsigned int call_count = 0; call_count += 1; //std::unique_lock lock(traceThreadMutex, std::try_to_lock); const bool is_tracing = tracing.load(std::memory_order_acquire); if (state == STATES::EXIT && !is_tracing) { OnOK(); } if (!is_tracing) { Transit(STATES::IDLE); } else if ((call_count % 10 == 0)) { if (state == STATES::TRACING) Transit(STATES::TRACING); else if (state == STATES::STOPPING) Transit(STATES::STOPPING); } CDialog::OnTimer(nIDEvent); } void WinMTRDialog::OnClose() { Transit(STATES::EXIT); } void WinMTRDialog::OnBnClickedCancel() { Transit(STATES::EXIT); }
6,795
C++
.cpp
237
25.987342
105
0.73718
leeter/WinMTR-refresh
36
6
5
GPL-2.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,743
WinMTRMain.cpp
leeter_WinMTR-refresh/WinMTRMain.cpp
/* WinMTR Copyright (C) 2010-2019 Appnor MSP S.A. - http://www.appnor.com Copyright (C) 2019-2021 Leetsoftwerx This program 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; version 2 of the License. This program 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 this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ //***************************************************************************** // FILE: WinMTRMain.cpp // // // HISTORY: // // // -- versions 0.8 // // - 01.18.2002 - Store LRU hosts in registry (v0.8) // - 05.08.2001 - Replace edit box with combo box which hold last entered hostnames. // Fixed a memory leak which caused program to crash after a long // time running. (v0.7) // - 11.27.2000 - Added resizing support and flat buttons. (v0.6) // - 11.26.2000 - Added copy data to clipboard and posibility to save data to file as text or HTML.(v0.5) // - 08.03.2000 - added double-click on hostname for detailed information (v0.4) // - 08.02.2000 - fix icmp error codes handling. (v0.3) // - 08.01.2000 - support for full command-line parameter specification (v0.2) // - 07.30.2000 - support for command-line host specification // by Silviu Simen (ssimen@ubisoft.ro) (v0.1b) // - 07.28.2000 - first release (v0.1) //***************************************************************************** #include "WinMTRGlobal.h" #include <locale> #include "WinMTRMain.h" import WinMTR.Help; import <winrt/Windows.Foundation.h>; import WinMTR.CommandLineParser; import WinMTR.Dialog; #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #pragma comment(linker,"\"/manifestdependency:type='win32' \ name='Microsoft.Windows.Common-Controls' version='6.0.0.0' \ processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"") WinMTRMain WinMTRinst; //***************************************************************************** // BEGIN_MESSAGE_MAP // // //***************************************************************************** BEGIN_MESSAGE_MAP(WinMTRMain, CWinApp) ON_COMMAND(ID_HELP, CWinApp::OnHelp) END_MESSAGE_MAP() //***************************************************************************** // WinMTRMain::WinMTRMain // // //***************************************************************************** WinMTRMain::WinMTRMain() { } //***************************************************************************** // WinMTRMain::InitInstance // // //***************************************************************************** BOOL WinMTRMain::InitInstance() { std::locale::global(std::locale(".UTF8")); struct rt_apartment { rt_apartment() { winrt::init_apartment(winrt::apartment_type::single_threaded); } ~rt_apartment() noexcept { winrt::uninit_apartment(); } }apartment; /*if (!AfxSocketInit()) { AfxMessageBox(IDP_SOCKETS_INIT_FAILED); return FALSE; }*/ AfxEnableControlContainer(); #ifdef _AFXDLL Enable3dControls(); // Call this when using MFC in a shared DLL #endif WinMTRDialog mtrDialog; utils::CWinMTRCommandLineParser cmd_info(mtrDialog); ParseCommandLine(cmd_info); if (cmd_info.isAskingForHelp()) { WinMTRHelp mtrHelp; m_pMainWnd = &mtrHelp; mtrHelp.DoModal(); return FALSE; } m_pMainWnd = &mtrDialog; [[maybe_unused]] auto nResponse = mtrDialog.DoModal(); return FALSE; }
3,808
C++
.cpp
109
33.201835
106
0.615091
leeter/WinMTR-refresh
36
6
5
GPL-2.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,744
WinMTRDialog-display.cpp
leeter_WinMTR-refresh/WinMTRDialog-display.cpp
/* WinMTR Copyright (C) 2010-2019 Appnor MSP S.A. - http://www.appnor.com Copyright (C) 2019-2023 Leetsoftwerx This program 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; version 2 of the License. This program 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 this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ module; #pragma warning (disable : 4005) #include "targetver.h" #define WIN32_LEAN_AND_MEAN #include <afx.h> #include <afxext.h> #include <afxdisp.h> #ifndef _AFX_NO_AFXCMN_SUPPORT #include <afxcmn.h> #endif #include "resource.h" #include "WinMTRProperties.h" module WinMTR.Dialog:display; import :ClassDef; import <format>; import <string>; import <string_view>; import WinMTRVerUtil; import WinMTRIPUtils; import WinMTRUtils; using namespace std::literals; namespace { constexpr auto DEFAULT_PING_SIZE = 64; constexpr auto DEFAULT_INTERVAL = 1.0; constexpr auto DEFAULT_MAX_LRU = 128; constexpr auto DEFAULT_DNS = true; #define MTR_NR_COLS 9 constexpr wchar_t MTR_COLS[MTR_NR_COLS][10] = { L"Hostname", L"Nr", L"Loss %", L"Sent", L"Recv", L"Best", L"Avrg", L"Worst", L"Last" }; constexpr int MTR_COL_LENGTH[MTR_NR_COLS] = { 190, 30, 50, 40, 40, 50, 50, 50, 50 }; constexpr auto WINMTR_DIALOG_TIMER = 100; } //***************************************************************************** // BEGIN_MESSAGE_MAP // // //***************************************************************************** BEGIN_MESSAGE_MAP(WinMTRDialog, CDialog) ON_WM_PAINT() ON_WM_SIZE() ON_WM_SIZING() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(ID_RESTART, OnRestart) ON_BN_CLICKED(ID_OPTIONS, OnOptions) ON_BN_CLICKED(ID_CTTC, OnCTTC) ON_BN_CLICKED(ID_CHTC, OnCHTC) ON_BN_CLICKED(ID_EXPT, OnEXPT) ON_BN_CLICKED(ID_EXPH, OnEXPH) ON_NOTIFY(NM_DBLCLK, IDC_LIST_MTR, OnDblclkList) ON_CBN_SELCHANGE(IDC_COMBO_HOST, &WinMTRDialog::OnCbnSelchangeComboHost) ON_CBN_SELENDOK(IDC_COMBO_HOST, &WinMTRDialog::OnCbnSelendokComboHost) ON_CBN_CLOSEUP(IDC_COMBO_HOST, &WinMTRDialog::OnCbnCloseupComboHost) ON_WM_TIMER() ON_WM_CLOSE() ON_BN_CLICKED(IDCANCEL, &WinMTRDialog::OnBnClickedCancel) END_MESSAGE_MAP() //***************************************************************************** // WinMTRDialog::WinMTRDialog // // //***************************************************************************** WinMTRDialog::WinMTRDialog(CWnd* pParent) noexcept : CDialog(WinMTRDialog::IDD, pParent), interval(DEFAULT_INTERVAL), state(STATES::IDLE), transition(STATE_TRANSITIONS::IDLE_TO_IDLE), pingsize(DEFAULT_PING_SIZE), maxLRU(DEFAULT_MAX_LRU), useDNS(DEFAULT_DNS) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); wmtrnet = std::make_shared<WinMTRNet>(this); } //***************************************************************************** // WinMTRDialog::DoDataExchange // // //***************************************************************************** void WinMTRDialog::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Control(pDX, ID_OPTIONS, m_buttonOptions); DDX_Control(pDX, IDCANCEL, m_buttonExit); DDX_Control(pDX, ID_RESTART, m_buttonStart); DDX_Control(pDX, IDC_COMBO_HOST, m_comboHost); DDX_Control(pDX, IDC_LIST_MTR, m_listMTR); DDX_Control(pDX, IDC_STATICS, m_staticS); DDX_Control(pDX, IDC_STATICJ, m_staticJ); DDX_Control(pDX, ID_EXPH, m_buttonExpH); DDX_Control(pDX, ID_EXPT, m_buttonExpT); } //***************************************************************************** // WinMTRDialog::OnInitDialog // // //***************************************************************************** BOOL WinMTRDialog::OnInitDialog() { CDialog::OnInitDialog(); const auto verNumber = WinMTRVerUtil::getExeVersion(); #ifndef _WIN64 constexpr auto bitness = 32; #else constexpr auto bitness = 64; #endif const auto caption = std::format(L"WinMTR-Refresh v{} {} bit"sv, verNumber, bitness); SetTimer(1, WINMTR_DIALOG_TIMER, nullptr); SetWindowTextW(caption.c_str()); SetIcon(m_hIcon, TRUE); SetIcon(m_hIcon, FALSE); if (!statusBar.Create(this)) AfxMessageBox(L"Error creating status bar"); statusBar.GetStatusBarCtrl().SetMinHeight(23); UINT sbi[1] = { IDS_STRING_SB_NAME }; statusBar.SetIndicators(sbi); statusBar.SetPaneInfo(0, statusBar.GetItemID(0), SBPS_STRETCH, 0); // removing for now but leaving commenteded this goes to a domain buying site, so either they lost the domain or are // out of business. I'll fix this when that changes. //{ // Add appnor URL // //std::unique_ptr<CMFCLinkCtrl> m_pWndButton = std::make_unique<CMFCLinkCtrl>(); // if (!m_pWndButton.Create(_T("www.appnor.com"), WS_CHILD|WS_VISIBLE|WS_TABSTOP, CRect(0,0,0,0), &statusBar, 1234)) { // TRACE(_T("Failed to create button control.\n")); // return FALSE; // } // m_pWndButton.SetURL(L"http://www.appnor.com/?utm_source=winmtr&utm_medium=desktop&utm_campaign=software"); // // if(!statusBar.AddPane(1234,1)) { // AfxMessageBox(_T("Pane index out of range\nor pane with same ID already exists in the status bar"), MB_ICONERROR); // return FALSE; // } // // statusBar.SetPaneWidth(statusBar.CommandToIndex(1234), 100); // statusBar.AddPaneControl(&m_pWndButton, 1234, true); //} for (int i = 0; i < MTR_NR_COLS; i++) { m_listMTR.InsertColumn(i, MTR_COLS[i], LVCFMT_LEFT, MTR_COL_LENGTH[i], -1); } m_comboHost.SetFocus(); // We need to resize the dialog to make room for control bars. // First, figure out how big the control bars are. CRect rcClientStart; CRect rcClientNow; GetClientRect(rcClientStart); RepositionBars(AFX_IDW_CONTROLBAR_FIRST, AFX_IDW_CONTROLBAR_LAST, 0, reposQuery, rcClientNow); // Now move all the controls so they are in the same relative // position within the remaining client area as they would be // with no control bars. //CPoint ptOffset(rcClientNow.left - rcClientStart.left, //rcClientNow.top - rcClientStart.top); const auto ptOffset = rcClientNow.TopLeft() - rcClientStart.TopLeft(); CRect rcChild; CWnd* pwndChild = GetWindow(GW_CHILD); while (pwndChild) { pwndChild->GetWindowRect(rcChild); ScreenToClient(rcChild); rcChild.OffsetRect(ptOffset); pwndChild->MoveWindow(rcChild, FALSE); pwndChild = pwndChild->GetNextWindow(); } // Adjust the dialog window dimensions CRect rcWindow; GetWindowRect(rcWindow); rcWindow.right += rcClientStart.Width() - rcClientNow.Width(); rcWindow.bottom += rcClientStart.Height() - rcClientNow.Height(); MoveWindow(rcWindow, FALSE); // And position the control bars RepositionBars(AFX_IDW_CONTROLBAR_FIRST, AFX_IDW_CONTROLBAR_LAST, 0); InitRegistry(); if (m_autostart) { m_comboHost.SetWindowText(msz_defaulthostname.c_str()); OnRestart(); } return FALSE; } //***************************************************************************** // WinMTRDialog::OnSizing // // //***************************************************************************** void WinMTRDialog::OnSizing(UINT fwSide, LPRECT pRect) { CDialog::OnSizing(fwSide, pRect); int iWidth = (pRect->right) - (pRect->left); int iHeight = (pRect->bottom) - (pRect->top); if (iWidth < 600) pRect->right = pRect->left + 600; if (iHeight < 250) pRect->bottom = pRect->top + 250; } //***************************************************************************** // WinMTRDialog::OnSize // // //***************************************************************************** void WinMTRDialog::OnSize(UINT nType, int cx, int cy) { CDialog::OnSize(nType, cx, cy); CRect r; GetClientRect(&r); CRect lb; if (::IsWindow(m_staticS.m_hWnd)) { const auto dpi = GetDpiForWindow(m_staticS.m_hWnd); m_staticS.GetWindowRect(&lb); ScreenToClient(&lb); const auto scaledXOffset = MulDiv(10, dpi, 96); m_staticS.SetWindowPos(nullptr, lb.TopLeft().x, lb.TopLeft().y, r.Width() - lb.TopLeft().x - scaledXOffset, lb.Height(), SWP_NOMOVE | SWP_NOZORDER); } if (::IsWindow(m_staticJ.m_hWnd)) { const auto dpi = GetDpiForWindow(m_staticJ.m_hWnd); m_staticJ.GetWindowRect(&lb); ScreenToClient(&lb); const auto scaledXOffset = MulDiv(21, dpi, 96); m_staticJ.SetWindowPos(nullptr, lb.TopLeft().x, lb.TopLeft().y, r.Width() - scaledXOffset, lb.Height(), SWP_NOMOVE | SWP_NOZORDER); } if (::IsWindow(m_buttonExit.m_hWnd)) { const auto dpi = GetDpiForWindow(m_buttonExit.m_hWnd); m_buttonExit.GetWindowRect(&lb); ScreenToClient(&lb); const auto scaledXOffset = MulDiv(21, dpi, 96); m_buttonExit.SetWindowPos(nullptr, r.Width() - lb.Width() - scaledXOffset, lb.TopLeft().y, lb.Width(), lb.Height(), SWP_NOSIZE | SWP_NOZORDER); } if (::IsWindow(m_buttonExpH.m_hWnd)) { const auto dpi = GetDpiForWindow(m_buttonExpH.m_hWnd); m_buttonExpH.GetWindowRect(&lb); ScreenToClient(&lb); const auto scaledXOffset = MulDiv(21, dpi, 96); m_buttonExpH.SetWindowPos(nullptr, r.Width() - lb.Width() - scaledXOffset, lb.TopLeft().y, lb.Width(), lb.Height(), SWP_NOSIZE | SWP_NOZORDER); } if (::IsWindow(m_buttonExpT.m_hWnd)) { const auto dpi = GetDpiForWindow(m_buttonExpT.m_hWnd); m_buttonExpT.GetWindowRect(&lb); ScreenToClient(&lb); const auto scaledXOffset = MulDiv(103, dpi, 96); m_buttonExpT.SetWindowPos(nullptr, r.Width() - lb.Width() - scaledXOffset, lb.TopLeft().y, lb.Width(), lb.Height(), SWP_NOSIZE | SWP_NOZORDER); } if (::IsWindow(m_listMTR.m_hWnd)) { const auto dpi = GetDpiForWindow(m_listMTR.m_hWnd); m_listMTR.GetWindowRect(&lb); ScreenToClient(&lb); const auto scaledX = MulDiv(21, dpi, 96); const auto scaledY = MulDiv(25, dpi, 96); m_listMTR.SetWindowPos(nullptr, lb.TopLeft().x, lb.TopLeft().y, r.Width() - scaledX, r.Height() - lb.top - scaledY, SWP_NOMOVE | SWP_NOZORDER); } RepositionBars(AFX_IDW_CONTROLBAR_FIRST, AFX_IDW_CONTROLBAR_LAST, 0, reposQuery, r); RepositionBars(AFX_IDW_CONTROLBAR_FIRST, AFX_IDW_CONTROLBAR_LAST, 0); } //***************************************************************************** // WinMTRDialog::OnPaint // // //***************************************************************************** void WinMTRDialog::OnPaint() { if (IsIconic()) { CPaintDC dc(this); SendMessage(WM_ICONERASEBKGND, (WPARAM)dc.GetSafeHdc(), 0); const auto dpi = GetDpiForWindow(*this); const int cxIcon = GetSystemMetricsForDpi(SM_CXICON, dpi); const int cyIcon = GetSystemMetricsForDpi(SM_CYICON, dpi); CRect rect; GetClientRect(&rect); const int x = (rect.Width() - cxIcon + 1) / 2; const int y = (rect.Height() - cyIcon + 1) / 2; dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } //***************************************************************************** // WinMTRDialog::OnQueryDragIcon // // //***************************************************************************** HCURSOR WinMTRDialog::OnQueryDragIcon() { return (HCURSOR)m_hIcon; } //***************************************************************************** // WinMTRDialog::OnDblclkList // //***************************************************************************** void WinMTRDialog::OnDblclkList([[maybe_unused]] NMHDR* pNMHDR, LRESULT* pResult) { using namespace std::string_view_literals; *pResult = 0; if (state == STATES::TRACING) { POSITION pos = m_listMTR.GetFirstSelectedItemPosition(); if (pos != nullptr) { int nItem = m_listMTR.GetNextSelectedItem(pos); WinMTRProperties wmtrprop; if (const auto lstate = wmtrnet->getStateAt(nItem); !isValidAddress(lstate.addr)) { wmtrprop.host.clear(); wmtrprop.ip.clear(); wmtrprop.comment = lstate.getName(); wmtrprop.pck_loss = wmtrprop.pck_sent = wmtrprop.pck_recv = 0; wmtrprop.ping_avrg = wmtrprop.ping_last = 0.0; wmtrprop.ping_best = wmtrprop.ping_worst = 0.0; } else { wmtrprop.host = lstate.getName(); wmtrprop.ip = addr_to_string(lstate.addr); wmtrprop.comment = L"Host alive."sv; wmtrprop.ping_avrg = static_cast<float>(lstate.getAvg()); wmtrprop.ping_last = static_cast<float>(lstate.last); wmtrprop.ping_best = static_cast<float>(lstate.best); wmtrprop.ping_worst = static_cast<float>(lstate.worst); wmtrprop.pck_loss = lstate.getPercent(); wmtrprop.pck_recv = lstate.returned; wmtrprop.pck_sent = lstate.xmit; } wmtrprop.DoModal(); } } } //***************************************************************************** // WinMTRDialog::SetHostName // //***************************************************************************** void WinMTRDialog::SetHostName(std::wstring host) { m_autostart = true; msz_defaulthostname = std::move(host); } //***************************************************************************** // WinMTRDialog::SetPingSize // //***************************************************************************** void WinMTRDialog::SetPingSize(unsigned ps, options_source fromCmdLine) noexcept { pingsize = ps; hasPingsizeFromCmdLine = static_cast<bool>(fromCmdLine); } //***************************************************************************** // WinMTRDialog::SetMaxLRU // //***************************************************************************** void WinMTRDialog::SetMaxLRU(int mlru, options_source fromCmdLine) noexcept { maxLRU = mlru; hasMaxLRUFromCmdLine = static_cast<bool>(fromCmdLine); } //***************************************************************************** // WinMTRDialog::SetInterval // //***************************************************************************** void WinMTRDialog::SetInterval(float i, options_source fromCmdLine) noexcept { interval = i; hasMaxLRUFromCmdLine = static_cast<bool>(fromCmdLine); } //***************************************************************************** // WinMTRDialog::SetUseDNS // //***************************************************************************** void WinMTRDialog::SetUseDNS(bool udns, options_source fromCmdLine) noexcept { useDNS = udns; hasUseDNSFromCmdLine = static_cast<bool>(fromCmdLine); } //***************************************************************************** // WinMTRDialog::WinMTRDialog // // //***************************************************************************** void WinMTRDialog::OnCancel() { } //***************************************************************************** // WinMTRDialog::DisplayRedraw // // //***************************************************************************** int WinMTRDialog::DisplayRedraw() { wchar_t buf[255] = {}, nr_crt[255] = {}; const auto netstate = wmtrnet->getCurrentState(); const auto nh = netstate.size(); while (m_listMTR.GetItemCount() > nh) { m_listMTR.DeleteItem(m_listMTR.GetItemCount() - 1); } static CString noResponse((LPCWSTR)IDS_STRING_NO_RESPONSE_FROM_HOST); for (int i = 0; const auto & host : netstate) { auto name = host.getName(); if (name.empty()) { name = noResponse; } auto result = std::format_to_n(nr_crt, std::size(nr_crt) - 1, WinMTRUtils::int_number_format, i + 1); *result.out = '\0'; if (m_listMTR.GetItemCount() <= i) m_listMTR.InsertItem(i, name.c_str()); else m_listMTR.SetItem(i, 0, LVIF_TEXT, name.c_str(), 0, 0, 0, 0); m_listMTR.SetItem(i, 1, LVIF_TEXT, nr_crt, 0, 0, 0, 0); constexpr auto writable_size = std::size(buf) - 1; result = std::format_to_n(buf, writable_size, WinMTRUtils::int_number_format, host.getPercent()); *result.out = '\0'; m_listMTR.SetItem(i, 2, LVIF_TEXT, buf, 0, 0, 0, 0); result = std::format_to_n(buf, writable_size, WinMTRUtils::int_number_format, host.xmit); *result.out = '\0'; m_listMTR.SetItem(i, 3, LVIF_TEXT, buf, 0, 0, 0, 0); result = std::format_to_n(buf, writable_size, WinMTRUtils::int_number_format, host.returned); *result.out = '\0'; m_listMTR.SetItem(i, 4, LVIF_TEXT, buf, 0, 0, 0, 0); result = std::format_to_n(buf, writable_size, WinMTRUtils::int_number_format, host.best); *result.out = '\0'; m_listMTR.SetItem(i, 5, LVIF_TEXT, buf, 0, 0, 0, 0); result = std::format_to_n(buf, writable_size, WinMTRUtils::int_number_format, host.getAvg()); *result.out = '\0'; m_listMTR.SetItem(i, 6, LVIF_TEXT, buf, 0, 0, 0, 0); result = std::format_to_n(buf, writable_size, WinMTRUtils::int_number_format, host.worst); *result.out = '\0'; m_listMTR.SetItem(i, 7, LVIF_TEXT, buf, 0, 0, 0, 0); result = std::format_to_n(buf, writable_size, WinMTRUtils::int_number_format, host.last); *result.out = '\0'; m_listMTR.SetItem(i, 8, LVIF_TEXT, buf, 0, 0, 0, 0); i++; } return 0; } void WinMTRDialog::OnCbnSelchangeComboHost() { } void WinMTRDialog::OnCbnSelendokComboHost() { } void WinMTRDialog::OnCbnCloseupComboHost() { if (m_comboHost.GetCurSel() == m_comboHost.GetCount() - 1) { ClearHistory(); } }
17,100
C++
.cpp
464
34.625
150
0.615617
leeter/WinMTR-refresh
36
6
5
GPL-2.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,745
WinMTRNet-Getters.cpp
leeter_WinMTR-refresh/WinMTRNet-Getters.cpp
/* WinMTR Copyright (C) 2010-2019 Appnor MSP S.A. - http://www.appnor.com Copyright (C) 2019-2023 Leetsoftwerx This program 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; version 2 of the License. This program 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 this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ module; #pragma warning (disable : 4005) #include "targetver.h" #define WIN32_LEAN_AND_MEAN #define VC_EXTRALEAN #define NOMCX #define NOIME #define NOGDI #define NONLS #define NOAPISET #define NOSERVICE #define NOMINMAX #include <winsock2.h> module WinMTR.Net:Getters; import <cstring>; import <vector>; import <iterator>; import <mutex>; import WinMTRSNetHost; import WinMTRIPUtils; import :ClassDef; [[nodiscard]] inline bool operator==(const SOCKADDR_INET& lhs, const SOCKADDR_INET& rhs) noexcept { return std::memcmp(&lhs, &rhs, sizeof(SOCKADDR_INET)) == 0; } [[nodiscard]] std::vector<s_nethost> WinMTRNet::getCurrentState() const { std::unique_lock lock(ghMutex); auto max = GetMax(); auto end = std::cbegin(host); std::advance(end, max); return std::vector<s_nethost>(std::cbegin(host), end); } [[nodiscard]] int WinMTRNet::GetMax() const { std::unique_lock lock(ghMutex); int max = MAX_HOPS; // first match: traced address responds on ping requests, and the address is in the hosts list for (int i = 1; const auto & h : host) { if (h.addr == last_remote_addr) { max = i; break; } ++i; } // second match: traced address doesn't responds on ping requests if (max == MAX_HOPS) { while ((max > 1) && (host[max - 1].addr == host[max - 2].addr && isValidAddress(host[max - 1].addr))) max--; } return max; }
2,098
C++
.cpp
69
28.855072
110
0.750495
leeter/WinMTR-refresh
36
6
5
GPL-2.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,746
WinMTRDialog-exporter.cpp
leeter_WinMTR-refresh/WinMTRDialog-exporter.cpp
/* WinMTR Copyright (C) 2010-2019 Appnor MSP S.A. - http://www.appnor.com Copyright (C) 2019-2023 Leetsoftwerx This program 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; version 2 of the License. This program 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 this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ module; #pragma warning (disable : 4005) #include "targetver.h" #define WIN32_LEAN_AND_MEAN #include <afx.h> #include <afxext.h> #include <afxdisp.h> #ifndef _AFX_NO_AFXCMN_SUPPORT #include <afxcmn.h> #endif #include "resource.h" #include <winrt/Windows.ApplicationModel.DataTransfer.h> #include <winrt/Windows.Foundation.Diagnostics.h> module WinMTR.Dialog:exporter; import :ClassDef; import <string>; import <sstream>; import <string_view>; import <iterator>; import <format>; import <fstream>; import WinMTR.Net; import WinMTRSNetHost; using namespace std::literals; namespace { [[nodiscard]] std::wstring makeTextOutput(const WinMTRNet& wmtrnet) { std::wostringstream out_buf; out_buf << L"|-------------------------------------------------------------------------------------------|\r\n" \ L"| WinMTR statistics |\r\n" \ L"| Host - %% | Sent | Recv | Best | Avrg | Wrst | Last |\r\n" \ L"|-------------------------------------------------|------|------|------|------|------|------|\r\n"sv; std::ostream_iterator<wchar_t, wchar_t> out(out_buf); CString noResponse; noResponse.LoadStringW(IDS_STRING_NO_RESPONSE_FROM_HOST); for (const auto curr_state = wmtrnet.getCurrentState(); const auto & hop : curr_state) { auto name = hop.getName(); if (name.empty()) { name = noResponse; } std::format_to(out, L"| {:40} - {:4} | {:4} | {:4} | {:4} | {:4} | {:4} | {:4} |\r\n"sv, name, hop.getPercent(), hop.xmit, hop.returned, hop.best, hop.getAvg(), hop.worst, hop.last); } out_buf << L"|_________________________________________________|______|______|______|______|______|______|\r\n"sv; CString cs_tmp; (void)cs_tmp.LoadStringW(IDS_STRING_SB_NAME); out_buf << L" "sv << cs_tmp.GetString(); return out_buf.str(); } // jscpd:ignore-start std::wostream& makeHTMLOutput(WinMTRNet& wmtrnet, std::wostream& out) { out << L"<table>" \ L"<thead><tr><th>Host</th><th>%%</th><th>Sent</th><th>Recv</th><th>Best</th><th>Avrg</th><th>Wrst</th><th>Last</th></tr></thead><tbody>"sv; std::ostream_iterator<wchar_t, wchar_t> outitr(out); CString noResponse; noResponse.LoadStringW(IDS_STRING_NO_RESPONSE_FROM_HOST); for (const auto curr_state = wmtrnet.getCurrentState(); const auto & hop : curr_state) { auto name = hop.getName(); if (name.empty()) { name = noResponse; } std::format_to(outitr , L"<tr><td>{}</td><td>{}</td><td>{}</td><td>{}</td><td>{}</td><td>{}</td><td>{}</td><td>{}</td></tr>"sv , name , hop.getPercent() , hop.xmit , hop.returned , hop.best , hop.getAvg() , hop.worst , hop.last ); } out << L"</tbody></table>"sv; return out; } // jscpd:ignore-end } //***************************************************************************** // WinMTRDialog::OnCTTC // // //***************************************************************************** void WinMTRDialog::OnCTTC() noexcept { using namespace winrt::Windows::ApplicationModel::DataTransfer; const auto f_buf = makeTextOutput(*wmtrnet); auto dataPackage = DataPackage(); dataPackage.SetText(f_buf); Clipboard::SetContentWithOptions(dataPackage, nullptr); } //***************************************************************************** // WinMTRDialog::OnCHTC // // //***************************************************************************** void WinMTRDialog::OnCHTC() noexcept { using namespace winrt::Windows::ApplicationModel::DataTransfer; std::wostringstream out; makeHTMLOutput(*wmtrnet, out); const auto f_buf = out.str(); const auto htmlFormat = HtmlFormatHelper::CreateHtmlFormat(f_buf); auto dataPackage = DataPackage(); dataPackage.SetHtmlFormat(htmlFormat); Clipboard::SetContentWithOptions(dataPackage, nullptr); } //***************************************************************************** // WinMTRDialog::OnEXPT // // //***************************************************************************** void WinMTRDialog::OnEXPT() noexcept { const TCHAR BASED_CODE szFilter[] = _T("Text Files (*.txt)|*.txt|All Files (*.*)|*.*||"); CFileDialog dlg(FALSE, _T("TXT"), nullptr, OFN_HIDEREADONLY, szFilter, this); if (dlg.DoModal() == IDOK) { const auto f_buf = makeTextOutput(*wmtrnet); if (std::wfstream fp(dlg.GetPathName(), std::ios::binary | std::ios::out | std::ios::trunc); fp) { fp << f_buf << std::endl; } } } //***************************************************************************** // WinMTRDialog::OnEXPH // // //***************************************************************************** void WinMTRDialog::OnEXPH() noexcept { const TCHAR szFilter[] = _T("HTML Files (*.htm, *.html)|*.htm;*.html|All Files (*.*)|*.*||"); CFileDialog dlg(FALSE, _T("HTML"), nullptr, OFN_HIDEREADONLY, szFilter, this); if (dlg.DoModal() == IDOK) { if (std::wfstream fp(dlg.GetPathName(), std::ios::binary | std::ios::out | std::ios::trunc); fp) { fp << L"<!DOCTYPE html><html><head><meta charset=\"utf-8\"/><title>WinMTR Statistics</title><style>" \ L"td{padding:0.2rem 1rem;border:1px solid #000;}" L"table{border:1px solid #000;border-collapse:collapse;}" \ L"tbody tr:nth-child(even){background:#ccc;}</style></head><body>" \ L"<h1>WinMTR statistics</h1>"sv; makeHTMLOutput(*wmtrnet, fp) << L"</body></html>"sv << std::endl; } } }
6,216
C++
.cpp
171
33.894737
142
0.572686
leeter/WinMTR-refresh
36
6
5
GPL-2.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,747
WinMTRDialog-registry.cpp
leeter_WinMTR-refresh/WinMTRDialog-registry.cpp
/* WinMTR Copyright (C) 2010-2019 Appnor MSP S.A. - http://www.appnor.com Copyright (C) 2019-2023 Leetsoftwerx This program 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; version 2 of the License. This program 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 this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ module; #pragma warning (disable : 4005) #include "targetver.h" #define WIN32_LEAN_AND_MEAN #include <afx.h> #include <afxext.h> #include <afxdisp.h> #ifndef _AFX_NO_AFXCMN_SUPPORT #include <afxcmn.h> #endif #include "resource.h" module WinMTR.Dialog:registry; import :ClassDef; import <format>; import <string_view>; import WinMTRVerUtil; import WinMTR.Options; using namespace std::literals; namespace { static constexpr auto reg_host_fmt = L"Host{:d}"sv; const auto NrLRU_REG_KEY = L"NrLRU"; const auto config_key_name = LR"(Software\WinMTR\Config)"; const auto lru_key_name = LR"(Software\WinMTR\LRU)"; } //***************************************************************************** // WinMTRDialog::InitRegistry // // //***************************************************************************** BOOL WinMTRDialog::InitRegistry() noexcept { CRegKey versionKey; if (versionKey.Create(HKEY_CURRENT_USER, LR"(Software\WinMTR)", nullptr, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS) != ERROR_SUCCESS) { return FALSE; } static const auto WINMTR_VERSION = L"0.96"; static const auto WINMTR_LICENSE = L"GPL - GNU Public License"; static const auto WINMTR_HOMEPAGE = L"https://github.com/leeter/WinMTR-refresh"; versionKey.SetStringValue(L"Version", WinMTRVerUtil::getExeVersion().c_str()); versionKey.SetStringValue(L"License", WINMTR_LICENSE); versionKey.SetStringValue(L"HomePage", WINMTR_HOMEPAGE); CRegKey config_key; if (config_key.Create(versionKey, L"Config", nullptr, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS) != ERROR_SUCCESS) { return FALSE; } DWORD tmp_dword; if (config_key.QueryDWORDValue(L"PingSize", tmp_dword) != ERROR_SUCCESS) { tmp_dword = pingsize; config_key.SetDWORDValue(L"PingSize", tmp_dword); } else { if (!hasPingsizeFromCmdLine) pingsize = tmp_dword; } if (config_key.QueryDWORDValue(L"MaxLRU", tmp_dword) != ERROR_SUCCESS) { tmp_dword = maxLRU; config_key.SetDWORDValue(L"MaxLRU", tmp_dword); } else { if (!hasMaxLRUFromCmdLine) maxLRU = tmp_dword; } if (config_key.QueryDWORDValue(L"UseDNS", tmp_dword) != ERROR_SUCCESS) { tmp_dword = useDNS ? 1 : 0; config_key.SetDWORDValue(L"UseDNS", tmp_dword); } else { if (!hasUseDNSFromCmdLine) useDNS = (BOOL)tmp_dword; } if (config_key.QueryDWORDValue(L"Interval", tmp_dword) != ERROR_SUCCESS) { tmp_dword = static_cast<DWORD>(interval * 1000); config_key.SetDWORDValue(L"Interval", tmp_dword); } else { if (!hasIntervalFromCmdLine) interval = (float)tmp_dword / 1000.0; } CRegKey lru_key; if (lru_key.Create(versionKey, L"LRU", nullptr, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS) != ERROR_SUCCESS) return FALSE; if (lru_key.QueryDWORDValue(NrLRU_REG_KEY, tmp_dword) != ERROR_SUCCESS) { tmp_dword = nrLRU; lru_key.SetDWORDValue(NrLRU_REG_KEY, tmp_dword); } else { wchar_t key_name[20]; wchar_t str_host[NI_MAXHOST]; nrLRU = tmp_dword; constexpr auto key_name_size = std::size(key_name) - 1; for (int i = 0; i < maxLRU; i++) { auto result = std::format_to_n(key_name, key_name_size, reg_host_fmt, i + 1); *result.out = '\0'; auto value_size = static_cast<DWORD>(std::size(str_host)); if (lru_key.QueryStringValue(key_name, str_host, &value_size) == ERROR_SUCCESS) { str_host[value_size] = L'\0'; m_comboHost.AddString((CString)str_host); } } } m_comboHost.AddString(CString((LPCTSTR)IDS_STRING_CLEAR_HISTORY)); return TRUE; } void WinMTRDialog::ClearHistory() { DWORD tmp_dword; wchar_t key_name[20] = {}; CRegKey lru_key; lru_key.Open(HKEY_CURRENT_USER, LR"(Software\WinMTR\LRU)", KEY_ALL_ACCESS); constexpr auto key_name_size = std::size(key_name) - 1; for (int i = 0; i <= nrLRU; i++) { auto result = std::format_to_n(key_name, key_name_size, reg_host_fmt, i); *result.out = '\0'; lru_key.DeleteValue(key_name); } nrLRU = 0; tmp_dword = nrLRU; lru_key.SetDWORDValue(NrLRU_REG_KEY, tmp_dword); m_comboHost.Clear(); m_comboHost.ResetContent(); m_comboHost.AddString(CString((LPCSTR)IDS_STRING_CLEAR_HISTORY)); } //***************************************************************************** // WinMTRDialog::OnRestart // // //***************************************************************************** void WinMTRDialog::OnRestart() noexcept { // If clear history is selected, just clear the registry and listbox and return if (m_comboHost.GetCurSel() == m_comboHost.GetCount() - 1) { ClearHistory(); return; } CString sHost; if (state == STATES::IDLE) { m_comboHost.GetWindowTextW(sHost); sHost.TrimLeft(); sHost.TrimLeft(); if (sHost.IsEmpty()) { AfxMessageBox(L"No host specified!"); m_comboHost.SetFocus(); return; } m_listMTR.DeleteAllItems(); } if (state == STATES::IDLE) { if (InitMTRNet()) { if (m_comboHost.FindString(-1, sHost) == CB_ERR) { m_comboHost.InsertString(m_comboHost.GetCount() - 1, sHost); wchar_t key_name[20]; CRegKey lru_key; lru_key.Open(HKEY_CURRENT_USER, lru_key_name, KEY_ALL_ACCESS); if (nrLRU >= maxLRU) nrLRU = 0; nrLRU++; auto result = std::format_to_n(key_name, std::size(key_name) - 1, reg_host_fmt, nrLRU); *result.out = '\0'; lru_key.SetStringValue(key_name, static_cast<LPCWSTR>(sHost)); auto tmp_dword = static_cast<DWORD>(nrLRU); lru_key.SetDWORDValue(NrLRU_REG_KEY, tmp_dword); } Transit(STATES::TRACING); } } else { Transit(STATES::STOPPING); } } //***************************************************************************** // WinMTRDialog::OnOptions // // //***************************************************************************** void WinMTRDialog::OnOptions() { WinMTROptions optDlg; optDlg.SetPingSize(pingsize); optDlg.SetInterval(interval); optDlg.SetMaxLRU(maxLRU); optDlg.SetUseDNS(useDNS); optDlg.SetUseIPv4(useIPv4); optDlg.SetUseIPv6(useIPv6); if (IDOK == optDlg.DoModal()) { pingsize = optDlg.GetPingSize(); interval = optDlg.GetInterval(); maxLRU = optDlg.GetMaxLRU(); useDNS = optDlg.GetUseDNS(); useIPv4 = optDlg.GetUseIPv4(); useIPv6 = optDlg.GetUseIPv6(); /*HKEY hKey;*/ DWORD tmp_dword; wchar_t key_name[20]; { CRegKey config_key; config_key.Open(HKEY_CURRENT_USER, config_key_name, KEY_ALL_ACCESS); tmp_dword = pingsize; config_key.SetDWORDValue(L"PingSize", tmp_dword); tmp_dword = maxLRU; config_key.SetDWORDValue(L"MaxLRU", tmp_dword); tmp_dword = useDNS ? 1 : 0; config_key.SetDWORDValue(L"UseDNS", tmp_dword); tmp_dword = static_cast<DWORD>(interval * 1000); config_key.SetDWORDValue(L"Interval", tmp_dword); } if (maxLRU < nrLRU) { CRegKey lru_key; lru_key.Open(HKEY_CURRENT_USER, lru_key_name, KEY_ALL_ACCESS); constexpr auto key_name_size = std::size(key_name) - 1; for (int i = maxLRU; i <= nrLRU; i++) { auto result = std::format_to_n(key_name, key_name_size, reg_host_fmt, i); *result.out = '\0'; lru_key.DeleteValue(key_name); } nrLRU = maxLRU; tmp_dword = nrLRU; lru_key.SetDWORDValue(NrLRU_REG_KEY, tmp_dword); } } }
7,803
C++
.cpp
244
29.401639
91
0.671093
leeter/WinMTR-refresh
36
6
5
GPL-2.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,748
WinMTRNet-Tracing.cpp
leeter_WinMTR-refresh/WinMTRNet-Tracing.cpp
/* WinMTR Copyright (C) 2010-2019 Appnor MSP S.A. - http://www.appnor.com Copyright (C) 2019-2023 Leetsoftwerx This program 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; version 2 of the License. This program 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 this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ module; #pragma warning (disable : 4005) #include "targetver.h" #define WIN32_LEAN_AND_MEAN #define VC_EXTRALEAN #define NOMCX #define NOIME #define NOGDI #define NONLS #define NOAPISET #define NOSERVICE #define NOMINMAX #include <winsock2.h> #include <WS2tcpip.h> #include <Ipexport.h> module WinMTR.Net:Tracing; #ifdef DEBUG import <sstream>; #define TRACE_MSG(msg) \ { \ std::wostringstream dbg_msg(std::wostringstream::out); \ dbg_msg << msg << std::endl; \ OutputDebugStringW(dbg_msg.str().c_str()); \ } #else #define TRACE_MSG(msg) #endif import <string_view>; import <mutex>; import <cstring>; import <winrt/Windows.Foundation.h>; import "WinMTRICMPPIOdef.h"; import WinMTRIPUtils; import WinMTRICMPUtils; import :ClassDef; struct ICMPHandleTraits { using type = HANDLE; static void close(type value) noexcept { WINRT_VERIFY_(TRUE, ::IcmpCloseHandle(value)); } [[nodiscard]] static type invalid() noexcept { return INVALID_HANDLE_VALUE; } }; using IcmpHandle = winrt::handle_type<ICMPHandleTraits>; struct trace_thread final { trace_thread(const trace_thread&) = delete; trace_thread& operator=(const trace_thread&) = delete; trace_thread(trace_thread&&) = default; trace_thread& operator=(trace_thread&&) = default; trace_thread(ADDRESS_FAMILY af, UCHAR ttl) noexcept :ttl(ttl) { if (af == AF_INET) { icmpHandle.attach(IcmpCreateFile()); } else if (af == AF_INET6) { icmpHandle.attach(Icmp6CreateFile()); } } IcmpHandle icmpHandle; UCHAR ttl; }; [[nodiscard("The task should be awaited")]] winrt::Windows::Foundation::IAsyncAction WinMTRNet::DoTrace(std::stop_token stop_token, SOCKADDR_INET address) { tracing = true; ResetHops(); last_remote_addr = address; auto threadMaker = [&address, this, stop_token](UCHAR i) { trace_thread current{ address.si_family, static_cast<UCHAR>(i + 1) }; using namespace std::string_view_literals; TRACE_MSG(L"Thread with TTL="sv << current.ttl << L" started."sv); if (address.si_family == AF_INET) { return this->handleICMP(address.Ipv4, stop_token, current); } else if (address.si_family == AF_INET6) { return this->handleICMP(address.Ipv6, stop_token, current); } winrt::throw_hresult(HRESULT_FROM_WIN32(WSAEOPNOTSUPP)); }; std::stop_callback callback{ stop_token, [this]() noexcept { this->tracing = false; TRACE_MSG(L"Cancellation"); } }; //// one thread per TTL value co_await std::invoke([]<UCHAR ...threads>(std::integer_sequence<UCHAR, threads...>, auto threadMaker) { return winrt::when_all(std::invoke(threadMaker, threads)...); }, std::make_integer_sequence<UCHAR, MAX_HOPS>{}, threadMaker); TRACE_MSG(L"Tracing Ended"); } template<class T> requires std::is_same_v<sockaddr_in, T> || std::is_same_v<sockaddr_in6, T> constexpr SOCKADDR_INET to_sockaddr_inet(T addr) noexcept { if constexpr (std::is_same_v<sockaddr_in, T>) { return { .Ipv4 = addr }; } else { return { .Ipv6 = addr }; } } template<class T> [[nodiscard("The task should be awaited")]] winrt::Windows::Foundation::IAsyncAction WinMTRNet::handleICMP(T remote_addr, std::stop_token stop_token, trace_thread& current) { using namespace std::literals; using traits = icmp_ping_traits<T>; trace_thread mine = std::move(current); T local_addr = remote_addr; co_await winrt::resume_background(); using namespace std::string_view_literals; const auto nDataLen = this->options->getPingSize(); std::vector<std::byte> achReqData{ nDataLen, static_cast<std::byte>(32) }; //whitespaces std::vector<std::byte> achRepData{ reply_reply_buffer_size<T>(nDataLen) }; winrt::handle wait_handle{ CreateEventW(nullptr, FALSE, FALSE, nullptr) }; T* addr = reinterpret_cast<T*>(&local_addr); while (this->tracing) { // this is a backup for if the atomic above doesn't work if (stop_token.stop_requested()) [[unlikely]] { this->tracing = false; co_return; } // For some strange reason, ICMP API is not filling the TTL for icmp echo reply // Check if the current thread should be closed if (mine.ttl > this->GetMax()) break; // NOTE: some servers does not respond back everytime, if TTL expires in transit; e.g. : // ping -n 20 -w 5000 -l 64 -i 7 www.chinapost.com.tw -> less that half of the replies are coming back from 219.80.240.93 // but if we are pinging ping -n 20 -w 5000 -l 64 219.80.240.93 we have 0% loss // A resolution would be: // - as soon as we get a hop, we start pinging directly that hop, with a greater TTL // - a drawback would be that, some servers are configured to reply for TTL transit expire, but not to ping requests, so, // for these servers we'll have 100% loss const auto dwReplyCount = co_await IcmpSendEchoAsync(mine.icmpHandle.get(), wait_handle.get(), addr, mine.ttl, achReqData, achRepData); this->AddXmit(mine.ttl - 1); if (dwReplyCount) { auto icmp_echo_reply = reinterpret_cast<traits::reply_type_ptr>(achRepData.data()); TRACE_MSG(L"TTL "sv << mine.ttl << L" Status "sv << icmp_echo_reply->Status << L" Reply count "sv << dwReplyCount); switch (icmp_echo_reply->Status) { case IP_SUCCESS: [[likely]] case IP_TTL_EXPIRED_TRANSIT: this->addNewReturn(mine.ttl - 1, icmp_echo_reply->RoundTripTime); { auto naddr = traits::to_addr_from_ping(icmp_echo_reply); this->SetAddr(mine.ttl - 1, to_sockaddr_inet(naddr)); } break; case IP_BUF_TOO_SMALL: this->SetName(current.ttl - 1, L"Reply buffer too small."s); break; case IP_DEST_NET_UNREACHABLE: this->SetName(current.ttl - 1, L"Destination network unreachable."s); break; case IP_DEST_HOST_UNREACHABLE: this->SetName(current.ttl - 1, L"Destination host unreachable."s); break; case IP_DEST_PROT_UNREACHABLE: this->SetName(current.ttl - 1, L"Destination protocol unreachable."s); break; case IP_DEST_PORT_UNREACHABLE: this->SetName(current.ttl - 1, L"Destination port unreachable."s); break; case IP_NO_RESOURCES: this->SetName(current.ttl - 1, L"Insufficient IP resources were available."s); break; case IP_BAD_OPTION: this->SetName(current.ttl - 1, L"Bad IP option was specified."s); break; case IP_HW_ERROR: this->SetName(current.ttl - 1, L"Hardware error occurred."s); break; case IP_PACKET_TOO_BIG: this->SetName(current.ttl - 1, L"Packet was too big."s); break; case IP_REQ_TIMED_OUT: this->SetName(current.ttl - 1, L"Request timed out."s); break; case IP_BAD_REQ: this->SetName(current.ttl - 1, L"Bad request."s); break; case IP_BAD_ROUTE: this->SetName(current.ttl - 1, L"Bad route."s); break; case IP_TTL_EXPIRED_REASSEM: this->SetName(current.ttl - 1, L"The time to live expired during fragment reassembly."s); break; case IP_PARAM_PROBLEM: this->SetName(current.ttl - 1, L"Parameter problem."s); break; case IP_SOURCE_QUENCH: this->SetName(current.ttl - 1, L"Datagrams are arriving too fast to be processed and datagrams may have been discarded."s); break; case IP_OPTION_TOO_BIG: this->SetName(current.ttl - 1, L"An IP option was too big."s); break; case IP_BAD_DESTINATION: this->SetName(current.ttl - 1, L"Bad destination."s); break; case IP_GENERAL_FAILURE: default: this->SetName(current.ttl - 1, L"General failure."s); break; } const auto intervalInSec = this->options->getInterval() * 1s; const auto roundTripDuration = std::chrono::milliseconds(icmp_echo_reply->RoundTripTime); if (intervalInSec > roundTripDuration) { using namespace winrt; const auto sleepTime = intervalInSec - roundTripDuration; co_await std::chrono::duration_cast<winrt::Windows::Foundation::TimeSpan>(sleepTime); } } } /* end ping loop */ co_return; } winrt::fire_and_forget WinMTRNet::SetAddr(int at, SOCKADDR_INET addr) { { std::unique_lock lock(ghMutex); if (isValidAddress(host[at].addr) || !isValidAddress(addr)) { co_return; } host[at].addr = addr; //TRACE_MSG(L"Start DnsResolverThread for new address " << addr << L". Old addr value was " << host[at].addr); } if (!options->getUseDNS()) { co_return; } auto local_at = at; // this could happen after a cleanup is called, so keep this alive until the coroutine returns auto sharedThis = shared_from_this(); co_await winrt::resume_background(); wchar_t buf[NI_MAXHOST] = {}; auto tempaddr = sharedThis->GetAddr(local_at); if (const auto nresult = GetNameInfoW( reinterpret_cast<sockaddr*>(&tempaddr) , static_cast<socklen_t>(getAddressSize(tempaddr)) , buf , static_cast<DWORD>(std::size(buf)) , nullptr , 0 , 0); // zero on success !nresult) { sharedThis->SetName(local_at, buf); } else { sharedThis->SetName(local_at, addr_to_string(tempaddr)); } TRACE_MSG(L"DNS resolver thread stopped."); }
9,593
C++
.cpp
269
32.828996
137
0.714485
leeter/WinMTR-refresh
36
6
5
GPL-2.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,749
WinMTRICMPPIOdef.h
leeter_WinMTR-refresh/WinMTRICMPPIOdef.h
/* WinMTR Copyright (C) 2010-2019 Appnor MSP S.A. - http://www.appnor.com Copyright (C) 2019-2021 Leetsoftwerx This program 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; version 2 of the License. This program 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 this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #pragma once #pragma warning (disable : 4005) #include "targetver.h" #define WIN32_LEAN_AND_MEAN #define NOMINMAX #define NOMCX #define NOIME #define NOGDI #define NONLS #define NOAPISET #define NOSERVICE #include <WinSock2.h> #include <WS2tcpip.h> #include <minwindef.h> #include <winternl.h> //typedef struct _IO_STATUS_BLOCK { // union { // NTSTATUS Status; // PVOID Pointer; // } DUMMYUNIONNAME; // ULONG_PTR Information; //} IO_STATUS_BLOCK, * PIO_STATUS_BLOCK; // //typedef //VOID //(NTAPI* PIO_APC_ROUTINE) ( // IN PVOID ApcContext, // IN PIO_STATUS_BLOCK IoStatusBlock, // IN ULONG Reserved // ); #define PIO_APC_ROUTINE_DEFINED #include <iphlpapi.h> #include <icmpapi.h> #include <Ipexport.h>
1,465
C++
.h
50
28.12
79
0.778094
leeter/WinMTR-refresh
36
6
5
GPL-2.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,750
WinMTRProperties.h
leeter_WinMTR-refresh/WinMTRProperties.h
/* WinMTR Copyright (C) 2010-2019 Appnor MSP S.A. - http://www.appnor.com Copyright (C) 2019-2021 Leetsoftwerx This program 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; version 2 of the License. This program 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 this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ //***************************************************************************** // FILE: WinMTRProperties.h // // // DESCRIPTION: // // // NOTES: // // //***************************************************************************** #ifndef WINMTRPROPERTIES_H_ #define WINMTRPROPERTIES_H_ #pragma warning (disable : 4005) import <string>; #include "resource.h" //***************************************************************************** // CLASS: WinMTRLicense // // //***************************************************************************** class WinMTRProperties : public CDialog { public: WinMTRProperties(CWnd* pParent = NULL) noexcept; enum { IDD = IDD_DIALOG_PROPERTIES }; std::wstring host; std::wstring ip; std::wstring comment; float ping_last; float ping_best; float ping_avrg; float ping_worst; int pck_sent; int pck_recv; int pck_loss; CEdit m_editHost, m_editIP, m_editComment, m_editSent, m_editRecv, m_editLoss, m_editLast, m_editBest, m_editWorst, m_editAvrg; protected: virtual void DoDataExchange(CDataExchange* pDX); virtual BOOL OnInitDialog(); DECLARE_MESSAGE_MAP() }; #endif // ifndef WINMTRLICENSE_H_
1,968
C++
.h
68
26.882353
79
0.63099
leeter/WinMTR-refresh
36
6
5
GPL-2.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,751
WinMTRGlobal.h
leeter_WinMTR-refresh/WinMTRGlobal.h
/* WinMTR Copyright (C) 2010-2019 Appnor MSP S.A. - http://www.appnor.com Copyright (C) 2019-2021 Leetsoftwerx This program 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; version 2 of the License. This program 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 this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ //***************************************************************************** // FILE: WinMTRGlobal.h // // // DESCRIPTION: // // // NOTES: // // //***************************************************************************** #pragma once #ifndef WINMTR_GLOBAL_H_ #define WINMTR_GLOBAL_H_ #pragma warning (disable : 4005) #include "targetver.h" #define WIN32_LEAN_AND_MEAN #define VC_EXTRALEAN #include <afxwin.h> #include <afxext.h> #include <afxdisp.h> #ifndef _AFX_NO_AFXCMN_SUPPORT #include <afxcmn.h> #endif #define SAVED_PINGS 100 constexpr auto MaxHost = 256; //#define MaxSequence 65536 #define MaxSequence 32767 //#define MaxSequence 5 //#define MAXPACKET 4096 //#define MINPACKET 64 //#define MaxTransit 4 //#define ICMP_ECHO 8 //#define ICMP_ECHOREPLY 0 // //#define ICMP_TSTAMP 13 //#define ICMP_TSTAMPREPLY 14 // //#define ICMP_TIME_EXCEEDED 11 // //#define ICMP_HOST_UNREACHABLE 3 // //#define MAX_UNKNOWN_HOSTS 10 //#define IP_HEADER_LENGTH 20 #ifdef DEBUG #include <sstream> #define TRACE_MSG(msg) \ { \ std::wostringstream dbg_msg(std::wostringstream::out); \ dbg_msg << msg << std::endl; \ OutputDebugStringW(dbg_msg.str().c_str()); \ } #else #define TRACE_MSG(msg) #endif #endif // ifndef WINMTR_GLOBAL_H_
2,057
C++
.h
72
27.097222
79
0.68413
leeter/WinMTR-refresh
36
6
5
GPL-2.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,752
WinMTRMain.h
leeter_WinMTR-refresh/WinMTRMain.h
/* WinMTR Copyright (C) 2010-2019 Appnor MSP S.A. - http://www.appnor.com Copyright (C) 2019-2021 Leetsoftwerx This program 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; version 2 of the License. This program 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 this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ //***************************************************************************** // FILE: WinMTRMain.h // // // DESCRIPTION: // // // NOTES: // // //***************************************************************************** #ifndef WINMTRMAIN_H_ #define WINMTRMAIN_H_ #include <afxwin.h> //***************************************************************************** // CLASS: WinMTRMain // // //***************************************************************************** class WinMTRMain final : public CWinApp { public: WinMTRMain(); virtual BOOL InitInstance() override final; DECLARE_MESSAGE_MAP() private: }; #endif // ifndef WINMTRMAIN_H_
1,435
C++
.h
44
31.068182
79
0.59114
leeter/WinMTR-refresh
36
6
5
GPL-2.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,753
resource.h
leeter_WinMTR-refresh/resource.h
//{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by WinMTR.rc // #define IDD_WINMTR_DIALOG 102 #define IDP_SOCKETS_INIT_FAILED 103 #define IDS_STRING_SB_NAME 104 #define IDS_STRING_SB_PING 105 #define IDS_STRING_CLEAR_HISTORY 106 #define IDS_STRING_UNABLE_TO_RESOLVE_HOSTNAME 107 #define IDS_STRING_STOP 108 #define IDS_STRING_START 109 #define IDS_STRING_WAITING_STOP_TRACE 110 #define IDS_STRING_DBL_CLICK_MORE_INFO 111 #define IDS_STRING_NO_RESPONSE_FROM_HOST 112 #define IDR_MAINFRAME 128 #define IDD_DIALOG_OPTIONS 129 #define IDD_DIALOG_LICENSE 130 #define IDD_DIALOG_PROPERTIES 131 #define IDD_DIALOG_HELP 132 #define IDC_EDIT_HOST 1000 #define IDC_LIST_MTR 1001 #define ID_RESTART 1002 #define ID_OPTIONS 1003 #define IDC_EDIT_INTERVAL 1004 #define ID_CTTC 1004 #define IDC_EDIT_SIZE 1005 #define ID_CHTC 1005 #define IDC_CHECK_DNS 1006 #define ID_EXPT 1006 #define ID_EXPH 1007 #define ID_LICENSE 1008 #define IDC_EDIT_LICENSE 1011 #define IDC_EDIT_PHOST 1012 #define IDC_EDIT_PIP 1013 #define IDC_EDIT_PSENT 1014 #define IDC_EDIT_PRECV 1015 #define IDC_EDIT_PLOSS 1016 #define IDC_EDIT_PLAST 1017 #define IDC_EDIT_PBEST 1018 #define IDC_EDIT_PAVRG 1019 #define IDC_EDIT_PWORST 1020 #define IDC_EDIT_PCOMMENT 1021 #define IDC_STATICS 1022 #define IDC_STATICJ 1023 #define IDC_COMBO_HOST 1024 #define IDC_EDIT_MAX_LRU 1025 #define IDC_MFCLINK1 1026 #define IDC_IPV4_CHECK 1027 #define IDC_USEIPV6_CHECK 1028 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 138 #define _APS_NEXT_COMMAND_VALUE 32771 #define _APS_NEXT_CONTROL_VALUE 1029 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif
2,450
C++
.h
60
39.8
49
0.559648
leeter/WinMTR-refresh
36
6
5
GPL-2.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,754
main.cpp
iRath96_variance-aware-path-guiding/visualizer/src/main.cpp
/* This file was adapted from nanogui/src/example1.cpp which is governed by a BSD-style license that can be found in the nanogui/LICENSE.txt file. Copyright (c) 2017 by ETH Zurich, Thomas Mueller. */ #include <nanogui/opengl.h> #include <nanogui/glutil.h> #include <nanogui/screen.h> #include <nanogui/window.h> #include <nanogui/layout.h> #include <nanogui/label.h> #include <nanogui/button.h> #include <nanogui/entypo.h> #include <nanogui/textbox.h> #include <nanogui/slider.h> #include <nanogui/imageview.h> #include <iostream> #include <string> #include <fstream> #include <vector> #include <iomanip> // setprecision #include <sstream> // stringstream #include <memory> #define _USE_MATH_DEFINES #include <math.h> using namespace Eigen; using namespace nanogui; using namespace std; class BlobReader { public: BlobReader(const std::string& filename) : f(filename, std::ios::in | std::ios::binary) {} std::string readString() { uint32_t length; f.read(reinterpret_cast<char*>(&length), sizeof(length)); std::string result; result.resize(length); f.read((char *)result.data(), length); return result; } template <typename Type> typename std::enable_if<std::is_standard_layout<Type>::value, BlobReader&>::type operator >> (Type& Element) { uint16_t size; Read(&size, 1); if (size != sizeof(Type)) { printf("Tried to read element of size %d but got %d", (int)sizeof(Type), (int)size); exit(-1); } Read(&Element, 1); return *this; } // CAUTION: This function may break down on big-endian architectures. // The ordering of bytes has to be reverted then. template <typename T> void Read(T* Dest, size_t Size) { f.read(reinterpret_cast<char*>(Dest), Size * sizeof(T)); } bool isValid() const { return (bool)(f); } private: std::ifstream f; }; static const int NUM_CHANNELS = 1; struct QuadTreeNode { array<array<float, 4>, NUM_CHANNELS> data; array<uint16_t, 4> children; inline bool isLeaf(int index) const { return children[index] == 0; } int computeDepth(const vector<QuadTreeNode>& nodes) const { int maxDepth = 0; for (int i = 0; i < 4; ++i) { if (!isLeaf(i)) { maxDepth = max(maxDepth, nodes[children[i]].computeDepth(nodes) + 1); } } return maxDepth; } float computeMax(const vector<QuadTreeNode>& nodes) const { float maximum = 0; for (int i = 0; i < 4; ++i) { if (!isLeaf(i)) { maximum = max(maximum, nodes[children[i]].computeMax(nodes)); } else { maximum = max(maximum, data[0][i]); } } return 4 * maximum; } int getChildIndex(Vector2f& p) const { if (p.x() < 0.5f) { p.x() *= 2; if (p.y() < 0.5f) { p.y() *= 2; return 0; } else { p.y() = (p.y() - 0.5f) * 2; return 1; } } else { p.x() = (p.x() - 0.5f) * 2; if (p.y() < 0.5f) { p.y() *= 2; return 2; } else { p.y() = (p.y() - 0.5f) * 2; return 3; } } } float eval(int index, Vector2f& p, const vector<QuadTreeNode>& nodes) const { const int c = getChildIndex(p); if (isLeaf(c)) { return data[index][c]; } else { return 4 * nodes[children[c]].eval(index, p, nodes); } } }; class DTree { public: const Vector3f& pos() const { return mPos; } float mean() const { return mMean; } float step() const { int dim = 1 << mDepth; return 1.0f / dim; } size_t nSamples() const { return mNumSamples; } bool read(BlobReader& blob) { uint64_t numNodes; float numSamples; int maxDepth; blob >> (float&)mMean >> (float&)numSamples >> (uint64_t&)numNodes >> (int&)maxDepth >> (float&)auxiliary; float tmp1; int tmp2; blob >> (float&)tmp1; blob >> (int&)tmp2; for (int i = 0; i < 3; ++i) blob >> (float&)tmp1; if (!blob.isValid()) { return false; } mNumSamples = (size_t)numSamples; if (!isfinite(mMean)) { cerr << "INVALID MEAN: " << mMean << endl; } mNodes.resize(numNodes); for (size_t i = 0; i < mNodes.size(); ++i) { auto& n = mNodes[i]; for (int j = 0; j < 4; ++j) { for (int k = 0; k < NUM_CHANNELS; ++k) { blob >> n.data[k][j]; if (!isfinite(n.data[k][j])) { cerr << "INVALID NODE: " << n.data[k][j] << endl; } } blob >> n.children[j]; } } mDepth = computeDepth(); mMax = computeMax(); return true; } float eval(int index, Vector2f p) const { if (mNumSamples == 0) { return 0; } const float factor = 1 / (float)(M_PI * mNumSamples); return factor * mNodes[0].eval(index, p, mNodes); } float evalIndex(int i, const Vector2i& index) const { const float localStep = step(); const float offset = localStep * 0.5f; return mean() > 0 ? (eval(i, {1.0f - (index.y() * localStep + offset), index.x() * localStep + offset}) / mean()) : mean(); } int loadData(vector<float>& data, int index) const { int dim = 1 << mDepth; float step = 1.0f / dim; float offset = step * 0.5f; float normFactor = mean() > 0 ? (1 / mean()) : mean(); data.resize(dim * dim); #pragma omp parallel for for (int i = 0; i < dim; ++i) { for (int j = 0; j < dim; ++j) { data[i * dim + j] = eval(index, {1.0f - (offset + step * i), offset + step * j}) * normFactor; } } return dim; } private: int computeDepth() const { return mNodes[0].computeDepth(mNodes) + 1; } float computeMax() const { if (mNumSamples == 0) { return 0; } const float factor = 1 / (float)(4 * M_PI * mNumSamples); return factor * mNodes[0].computeMax(mNodes); } int depth() const { return mDepth; } public: Vector3f mPos; Vector3f mSize; float auxiliary; private: vector<QuadTreeNode> mNodes; float mMean; size_t mNumSamples; int mDepth; float mMax; }; class GLTexture { public: GLTexture() = default; GLTexture(const string& textureName) : mTextureName(textureName), mTextureId(0) { } GLTexture(GLTexture&& other) : mTextureName(move(other.mTextureName)), mTextureId(other.mTextureId) { other.mTextureId = 0; } GLTexture& operator=(GLTexture&& other) { mTextureName = move(other.mTextureName); swap(mTextureId, other.mTextureId); return *this; } ~GLTexture() { if (mTextureId) glDeleteTextures(1, &mTextureId); } GLuint texture(const DTree& dTree, int index) { load(dTree, index); return mTextureId; } const string& textureName() const { return mTextureName; } private: void load(const DTree& dTree, int index) { if (mTextureId) { glDeleteTextures(1, &mTextureId); mTextureId = 0; } vector<float> data; int dim = dTree.loadData(data, index); glGenTextures(1, &mTextureId); glBindTexture(GL_TEXTURE_2D, mTextureId); glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, dim, dim, 0, GL_RED, GL_FLOAT, &data[0]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glPointSize(2.0f); } string mTextureName; GLuint mTextureId; }; Vector2f dirToCanonical(const Vector3f& d) { const float cosTheta = std::min(std::max(d.z(), -1.0f), 1.0f); float phi = std::atan2(d.y(), d.x()); while (phi < 0) phi += 2.0 * M_PI; return {(cosTheta + 1) / 2, phi / (2 * M_PI)}; } Vector3f canonicalToDir(float x, float y) { const float cosTheta = 2 * x - 1; const float phi = 2 * M_PI * y; const float sinTheta = sqrt(1 - cosTheta * cosTheta); float sinPhi = sin(phi); float cosPhi = cos(phi); return {sinTheta * cosPhi, sinTheta * sinPhi, cosTheta}; }; class CustomImageView : public ImageView { public: CustomImageView(Widget* parent, GLuint imageID) : ImageView(parent, imageID) {} void setLookCallback(const std::function<void(const Vector3f&)>& callback) { mLookCallback = callback; } bool mouseMotionEvent(const Vector2i &p, const Vector2i &rel, int button, int modifiers) override { auto x = imageCoordinateAt(p.cast<float>()); auto y = imageSizeF(); auto v = canonicalToDir(x.x() / y.x(), 1.0f - (x.y() / y.y())); if (mLookCallback) { mLookCallback(v); } return true; } std::function<void(const Vector3f&)> mLookCallback; }; struct STree { array<CustomImageView*, NUM_CHANNELS> imageViews; array<GLTexture, NUM_CHANNELS> textures; vector<shared_ptr<DTree>> dTrees; Vector3f target; Vector3f eye; Vector3f up; size_t currentDTreeIndex = -1; float aabbDiag; }; inline char separator() { #ifdef _WIN32 return '\\'; #else return '/'; #endif } class SDTreeVisualizer : public Screen { public: SDTreeVisualizer() : Screen(Vector2i(1024, 768), "SD-Tree Visualizer") { glfwMaximizeWindow(mGLFWWindow); Window* window = new Window(this, "Controls"); window->setPosition(Vector2i(15, 15)); window->setLayout(new GroupLayout()); mImageContainer = new Window(this, "Samplingpoint dir"); mImageContainer->setPosition(Vector2i(mSize.x() - 256, 0)); mImageContainer->setLayout(new BoxLayout(Orientation::Vertical)); mImageContainer->setFixedWidth(256); new Label(window, "Loading distributions", "sans-bold"); Widget* tools = new Widget(window); tools->setLayout(new BoxLayout(Orientation::Horizontal, Alignment::Middle, 0, 6)); Button* b = new Button(tools, "Open", ENTYPO_ICON_FOLDER); b->setCallback([&] { string file = file_dialog({{"sdt", "Sampling distribution"}}, false); if (!file.empty()) { loadSDTree(file); } }); new Label(window, "Exposure", "sans-bold"); Widget *panel = new Widget(window); panel->setLayout(new BoxLayout(Orientation::Horizontal, Alignment::Middle, 0, 20)); mExposureSlider = new Slider(panel); mExposureSlider->setRange({-15.0f, 0.0f}); mExposureSlider->setValue(-9.0f); mExposureSlider->setFixedWidth(120); mExposureTextbox = new TextBox(panel); mExposureTextbox->setFixedSize(Vector2i(60, 25)); mExposureSlider->setCallback([this](float value) { setExposure(value); }); mExposureTextbox->setFixedSize(Vector2i(60, 25)); mExposureTextbox->setFontSize(20); mExposureTextbox->setAlignment(TextBox::Alignment::Right); setExposure(-9); mShader.init( "point_shader", /* Vertex shader */ "#version 330\n" "uniform mat4 modelViewProj;\n" "in vec3 position;\n" "in vec3 attrColor;\n" "out vec3 fragColor;\n" "void main() {\n" " gl_Position = modelViewProj * vec4(position, 1.0);\n" " fragColor = attrColor;" "}", /* Fragment shader */ "#version 330\n" "out vec4 color;\n" "in vec3 fragColor;\n" "void main() {\n" " color = vec4(fragColor, 1.0);\n" "}" ); lineShader.init( "line_shader", /* Vertex shader */ "#version 330\n" "uniform mat4 modelViewProj;\n" "in vec3 position;\n" "out vec3 fragColor;\n" "void main() {\n" " gl_Position = modelViewProj * vec4(position, 1.0);\n" " fragColor = vec3(1.0, 1.0, 1.0);" "}", /* Fragment shader */ "#version 330\n" "out vec4 color;\n" "in vec3 fragColor;\n" "void main() {\n" " color = vec4(fragColor, 1.0);\n" "}" ); performLayout(); } ~SDTreeVisualizer() { mShader.free(); lineShader.free(); } size_t totalPoints() const { size_t totalPoints = 0; for (const auto& sTree : mSDTrees) { totalPoints += sTree.dTrees.size(); } return totalPoints; } void updateLineShader(const Vector3f& x, const Vector3f& dir) { MatrixXf positions(3, 2); positions.col(0) = x; positions.col(1) = x + 3 * dir; lineShader.bind(); lineShader.uploadAttrib("position", positions); } void updateShader() { size_t nPoints = totalPoints(); // Draw our dTrees MatrixXu indices(1, nPoints); MatrixXf positions(3, nPoints); size_t idx = 0; for (const auto& sTree : mSDTrees) { for (size_t i = 0; i < sTree.dTrees.size(); ++i) { const auto& dTree = *sTree.dTrees[i]; indices.col(idx) << static_cast<unsigned int>(idx); positions.col(idx) = dTree.pos(); ++idx; } } mShader.bind(); mShader.uploadIndices(indices); mShader.uploadAttrib("position", positions); } float exposure() const { return mExposureSlider->value(); } void setExposure(float exposure) { mExposureSlider->setValue(exposure); for (auto& sTree : mSDTrees) { for (auto& v : sTree.imageViews) { v->setExposure(exposure); } } stringstream stream; stream << fixed << setprecision(2) << exposure; mExposureTextbox->setValue(stream.str()); } void loadSDTree(string filename) { size_t last = filename.find_last_of(separator()) + 1; new Label(mImageContainer, filename.substr(last, filename.size() - last), "sans-bold"); BlobReader reader(filename); std::cout << reader.readString() << std::endl; Matrix4f camera; for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { reader >> camera(i, j); } } if (mSDTrees.size() == 0) { mCamera = camera.inverse(); mCamera.row(0) *= -1; mCamera.row(2) *= -1; mUp = (mCamera.inverse().topLeftCorner(3, 3) * Vector3f(0, 1, 0)).normalized(); } mSDTrees.emplace_back(); STree& sTree = mSDTrees.back(); sTree.dTrees.clear(); /* read STree information */ size_t numNodes; Vector3f min, max; reader >> (size_t&)numNodes >> (float&)min.x() >> (float&)min.y() >> (float&)min.z() >> (float&)max.x() >> (float&)max.y() >> (float&)max.z(); struct STreeNode { bool isLeaf; shared_ptr<DTree> dTree; int axis; std::array<uint32_t, 2> children; void read(BlobReader& blob) { blob >> (bool&)isLeaf >> (int&)axis >> (uint32_t&)children[0] >> (uint32_t&)children[1] ; if (isLeaf) { dTree = shared_ptr<DTree>(new DTree()); dTree->read(blob); } } void traverse(Vector3f pos, Vector3f size, vector<STreeNode> &nodes, STree &sTree) { if (isLeaf) { //if (dTree->nSamples() < 100) // return; dTree->mPos = pos + size / 2; dTree->mSize = size; sTree.dTrees.emplace_back(move(dTree)); } else { size[axis] /= 2; Vector3f pos2 = pos; pos2[axis] += size[axis]; nodes[children[0]].traverse(pos , size, nodes, sTree); nodes[children[1]].traverse(pos2, size, nodes, sTree); } } }; vector<STreeNode> nodes; nodes.resize(numNodes); for (size_t i = 0; i < nodes.size(); ++i) { auto& node = nodes[i]; node.read(reader); } nodes[0].traverse(min, max - min, nodes, sTree); if (mSDTrees.size() == 1) { mAABBDiag = (max - min).norm(); } cout << "Loaded SD-Tree with " << sTree.dTrees.size() << " D-Trees." << endl; const auto& firstDTree = *sTree.dTrees[0]; Widget* buffers = new Widget(mImageContainer); buffers->setLayout(new BoxLayout(Orientation::Horizontal, Alignment::Middle, 0, 6)); size_t idx = mSDTrees.size() - 1; for (size_t i = 0; i < sTree.imageViews.size(); ++i) { sTree.imageViews[i] = new CustomImageView(buffers, sTree.textures[i].texture(firstDTree, (int)i)); sTree.imageViews[i]->setExposure(exposure()); sTree.imageViews[i]->setGridThreshold(20); sTree.imageViews[i]->setPixelInfoThreshold(20); sTree.imageViews[i]->setLookCallback( [this, idx, i](const Vector3f& dir) -> void { const STree& sTree = mSDTrees[idx]; auto& dTree = *sTree.dTrees[sTree.currentDTreeIndex]; updateLineShader(dTree.mPos, dir); } ); sTree.imageViews[i]->setPixelInfoCallback( [this, idx, i](const Vector2i& index) -> pair<string, Color> { const STree& sTree = mSDTrees[idx]; auto& dTree = *sTree.dTrees[sTree.currentDTreeIndex]; const float radiance = dTree.evalIndex((int)i, index); ostringstream oss; oss << radiance << "\n"; if (dTree.mean() > 0) { const float percent = 100 * dTree.step() * dTree.step() * radiance / dTree.mean(); oss << fixed; oss.precision(2); oss << percent << "%"; } Color textColor = Color(0.0f, 1.0f); return{oss.str(), textColor}; } ); } setDTree(sTree, 0); updateShader(); updateColors(); performLayout(); } void updateColors() { size_t nPoints = totalPoints(); MatrixXf colors(3, nPoints); size_t idx = 0; for (size_t j = 0; j < mSDTrees.size(); ++j) { const auto& sTree = mSDTrees[j]; size_t cIdx = j + 1; Color c((float)(cIdx & 1), (float)((cIdx & 2) >> 1), (float)((cIdx & 4) >> 2), 1.0f); for (int i = 0; i < 3; ++i) { c[i] += 0.5f; } for (size_t i = 0; i < sTree.dTrees.size(); ++i) { if (i == sTree.currentDTreeIndex) { colors.col(idx) << 1.0f, 1.0f, 1.0f; } else { colors.col(idx) << c[0], c[1], c[2]; } ++idx; } } mShader.bind(); mShader.uploadAttrib("attrColor", colors); } Vector2f pixelToCanonical(const Vector2i& p) { return {(float)p.x() / size().x(), (float)p.y() / size().y()}; } void setDTree(STree& sTree, size_t i) { if (sTree.currentDTreeIndex == i) { return; } sTree.currentDTreeIndex = i; DTree& dTree = *sTree.dTrees[i]; Vector2i imageSize = Vector2i(256, 256); for (size_t j = 0; j < sTree.imageViews.size(); ++j) { sTree.imageViews[j]->bindImage(sTree.textures[j].texture(dTree, (int)j)); sTree.imageViews[j]->setFixedSize(imageSize); sTree.imageViews[j]->setScale((float)imageSize.x() * dTree.step()); } updateColors(); } void updateDTree(STree& dist, const Vector2i &p) { // Obtain clicking point in [-1,1]^3 screen space. Vector2f point = (pixelToCanonical(p) * 2) - Vector2f{1, 1}; Vector3f pEye = eye(); // Map screen space point with some depth to scene point to obtain looking direction // of clicked location in world space. Vector4f dirHomo = mvp().inverse() * Vector4f(point.x(), -point.y(), 1, 1); Vector3f dir = (dirHomo.topRows(3) / dirHomo.w() - pEye).normalized(); auto distPointDir = [](Vector3f o, Vector3f dir, Vector3f p) { Vector3f difference = p - o; float d = difference.norm(); Vector3f toPoint = difference / d; float other = toPoint.dot(dir) * d; return sqrt(d * d - other * other); }; vector<size_t> nearPoints; float eyeDist = dir.dot(pEye); // Find sampling point with shortest distance to ray parametrized by // o = mEye and d = dir float minDist = numeric_limits<float>::infinity(); size_t minI = numeric_limits<size_t>::max(); for (size_t i = 0; i < dist.dTrees.size(); ++i) { float distance = distPointDir(pEye, dir, dist.dTrees[i]->pos()); if (distance < minDist) { minDist = distance; minI = i; } } if (minI == numeric_limits<size_t>::max()) { return; } // Visualize the selected sampling point setDTree(dist, minI); } bool dropEvent(const std::vector<std::string>& files) override { if (Screen::dropEvent(files)) { return true; } for (const auto& file : files) { loadSDTree(file); } return true; } bool mouseMotionEvent(const Vector2i &p, const Vector2i &rel, int button, int modifiers) override { if (Screen::mouseMotionEvent(p, rel, button, modifiers)) return true; bool isRightHeld = (button & 2) != 0; if (isRightHeld) { mShallUpdatePosition = true; mPositionToUpdate = p; } Vector2f relF = pixelToCanonical(rel); Vector3f side = mUp.cross(eye()).normalized(); if (modifiers == 2 && button == 1) button = 4; bool isLeftHeld = (button & 1) != 0; if (isLeftHeld) { // Spin camera around target Matrix4f rot; rot.setIdentity(); rot.topLeftCorner<3, 3>() = Matrix3f( AngleAxisf(static_cast<float>(relF.x() * 2 * M_PI), mUp) * // Scroll sideways around up vector AngleAxisf(static_cast<float>(relF.y() * 2 * M_PI), side) // Scroll around side vector ); mCamera *= rot; } bool isMiddleHeld = (button & 4) != 0; if (isMiddleHeld) { // Translate camera Matrix4f trans; trans.setIdentity(); trans.topRightCorner<3, 1>() += (-mUp * relF.y() + side * relF.x()) * mAABBDiag; mCamera *= trans; } return true; } bool mouseButtonEvent(const Vector2i &p, int button, bool down, int modifiers) override { if (Screen::mouseButtonEvent(p, button, down, modifiers)) return true; bool isRightDown = down && button == 1; if (isRightDown) { mShallUpdatePosition = true; mPositionToUpdate = p; } return true; } bool scrollEvent(const Vector2i &p, const Vector2f &rel) override { if (Screen::scrollEvent(p, rel)) return true; float scale = pow(1.1f, rel.y()); mCamera.topRightCorner<3, 1>() /= scale; return true; } bool keyboardEvent(int key, int scancode, int action, int modifiers) override { if (Screen::keyboardEvent(key, scancode, action, modifiers)) return true; if ((key == GLFW_KEY_ESCAPE || key == GLFW_KEY_Q) && action == GLFW_PRESS) { setVisible(false); return true; } if (key == GLFW_KEY_E && (action == GLFW_PRESS || action == GLFW_REPEAT)) { if (modifiers & 1) { setExposure(exposure() - 0.5f); } else { setExposure(exposure() + 0.5f); } cout << "Exposure set to " << exposure() << endl; return true; } return false; } void syncImageViews() { // Sync up image views const auto& first = mSDTrees.front().imageViews.front(); float firstStep = mSDTrees.front().dTrees[mSDTrees.front().currentDTreeIndex]->step(); for (auto& sTree : mSDTrees) { float step = sTree.dTrees[sTree.currentDTreeIndex]->step(); for (auto& v : sTree.imageViews) { if (v == first) { continue; } v->setScale(step * first->scale() / firstStep); v->setOffset(first->offset()); } } } void draw(NVGcontext *ctx) override { if (!mSDTrees.empty()) { syncImageViews(); } if (mShallUpdatePosition) { for (auto& sTree : mSDTrees) { updateDTree(sTree, mPositionToUpdate); } mShallUpdatePosition = false; } Screen::draw(ctx); } Matrix4f proj() { Vector2i vSize = size(); float fov = 50 * static_cast<float>(M_PI / 180); float aspect = (float)vSize.x() / vSize.y(); float xScale = 1 / tan(fov / 2); float yScale = xScale * aspect; float zFar = 10000; float zNear = 0.01f; Matrix4f proj; proj << xScale, 0, 0, 0, 0, yScale, 0, 0, 0, 0, -(zFar + zNear) / (zFar - zNear), -1, 0, 0, -2 * zNear*zFar / (zFar - zNear), 0; return proj.transpose(); } Matrix4f mvp() { return proj() * mCamera; } Vector3f eye() { Vector4f eyeHomo = mCamera.inverse() * Vector4f(0, 0, 0, 1); return eyeHomo.topRows(3) / eyeHomo.w(); } void drawContents() override { mShader.bind(); mShader.setUniform("modelViewProj", mvp()); mShader.drawIndexed(GL_POINTS, 0, static_cast<uint32_t>(totalPoints())); lineShader.bind(); lineShader.setUniform("modelViewProj", mvp()); lineShader.drawArray(GL_LINES, 0, 2); } private: GLShader mShader; GLShader lineShader; TextBox* mExposureTextbox; Slider* mExposureSlider; Widget* mImageContainer; vector<STree> mSDTrees; Matrix4f mCamera; Vector3f mUp; float mAABBDiag; Vector2i mPositionToUpdate; bool mShallUpdatePosition = false; }; int main(int argc, char* argv[]) { try { init(); { auto app = unique_ptr<SDTreeVisualizer>(new SDTreeVisualizer()); app->setBackground(Color(0.0f, 0.0f, 0.0f, 1.0f)); app->drawAll(); app->setVisible(true); for (int i = 1; i < argc; ++i) { app->loadSDTree(argv[i]); } mainloop(); } // glfwTerminate(), which is called by shutdown(), causes segmentation // faults on various linux distributions. Let's let the OS clean up // behind us and not crash in the last second. //shutdown(); } catch (const runtime_error &e) { cerr << "Uncaught exception: " << e.what() << endl; return 1; } return 0; }
28,819
C++
.cpp
800
26.06125
131
0.534568
iRath96/variance-aware-path-guiding
35
7
0
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,755
guided_path.cpp
iRath96_variance-aware-path-guiding/mitsuba/src/integrators/path/guided_path.cpp
/* This file is part of Mitsuba, a physically based rendering system. Copyright (c) 2007-2014 by Wenzel Jakob Copyright (c) 2017 by ETH Zurich, Thomas Mueller. Copyright (c) 2020 by Alexander Rath. Mitsuba is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License Version 3 as published by the Free Software Foundation. Mitsuba 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 this program. If not, see <http://www.gnu.org/licenses/>. */ // all additions for our paper "Variance-aware path guiding" // have been marked with "@addition" so they can easily be found using search #include <mitsuba/render/renderproc.h> #include <mitsuba/render/scene.h> #include <mitsuba/core/plugin.h> #include <mitsuba/core/statistics.h> #include <array> #include <atomic> #include <chrono> #include <fstream> #include <functional> #include <iomanip> #include <sstream> MTS_NAMESPACE_BEGIN class BlobReader { public: BlobReader(const std::string& filename) : f(filename, std::ios::in | std::ios::binary) {} std::string readString() { uint32_t length; f.read(reinterpret_cast<char*>(&length), sizeof(length)); std::string result; result.resize(length); f.read((char *)result.data(), length); return result; } template <typename Type> typename std::enable_if<std::is_standard_layout<Type>::value, BlobReader&>::type operator >> (Type& Element) { uint16_t size; Read(&size, 1); if (size != sizeof(Type)) { SLog(EError, "Tried to read element of size %d but got %d", (int)sizeof(Type), (int)size); } Read(&Element, 1); return *this; } // CAUTION: This function may break down on big-endian architectures. // The ordering of bytes has to be reverted then. template <typename T> void Read(T* Dest, size_t Size) { f.read(reinterpret_cast<char*>(Dest), Size * sizeof(T)); } bool isValid() const { return (bool)(f); } private: std::ifstream f; }; class BlobWriter { public: BlobWriter(const std::string& filename) : f(filename, std::ios::out | std::ios::binary) { } void writeString(const std::string& str) { uint32_t length = str.length(); f.write(reinterpret_cast<const char*>(&length), sizeof(length)); f.write(str.c_str(), length); } template <typename Type> typename std::enable_if<std::is_standard_layout<Type>::value, BlobWriter&>::type operator << (Type Element) { uint16_t size = sizeof(Type); Write(&size, 1); Write(&Element, 1); return *this; } // CAUTION: This function may break down on big-endian architectures. // The ordering of bytes has to be reverted then. template <typename T> void Write(T* Src, size_t Size) { f.write(reinterpret_cast<const char*>(Src), Size * sizeof(T)); } private: std::ofstream f; }; static void addToAtomicFloat(std::atomic<Float>& var, Float val) { auto current = var.load(); while (!var.compare_exchange_weak(current, current + val)); } inline Float logistic(Float x) { return 1 / (1 + std::exp(-x)); } // Implements the stochastic-gradient-based Adam optimizer [Kingma and Ba 2014] class AdamOptimizer { public: AdamOptimizer(Float learningRate, int batchSize = 1, Float epsilon = 1e-08f, Float beta1 = 0.9f, Float beta2 = 0.999f) { m_hparams = { learningRate, batchSize, epsilon, beta1, beta2 }; } AdamOptimizer& operator=(const AdamOptimizer& arg) { m_state = arg.m_state; m_hparams = arg.m_hparams; return *this; } AdamOptimizer(const AdamOptimizer& arg) { *this = arg; } void append(Float gradient, Float statisticalWeight) { m_state.batchGradient += gradient * statisticalWeight; m_state.batchAccumulation += statisticalWeight; if (m_state.batchAccumulation > m_hparams.batchSize) { step(m_state.batchGradient / m_state.batchAccumulation); m_state.batchGradient = 0; m_state.batchAccumulation = 0; } } void step(Float gradient) { ++m_state.iter; Float actualLearningRate = m_hparams.learningRate * std::sqrt(1 - std::pow(m_hparams.beta2, m_state.iter)) / (1 - std::pow(m_hparams.beta1, m_state.iter)); m_state.firstMoment = m_hparams.beta1 * m_state.firstMoment + (1 - m_hparams.beta1) * gradient; m_state.secondMoment = m_hparams.beta2 * m_state.secondMoment + (1 - m_hparams.beta2) * gradient * gradient; m_state.variable -= actualLearningRate * m_state.firstMoment / (std::sqrt(m_state.secondMoment) + m_hparams.epsilon); // Clamp the variable to the range [-20, 20] as a safeguard to avoid numerical instability: // since the sigmoid involves the exponential of the variable, value of -20 or 20 already yield // in *extremely* small and large results that are pretty much never necessary in practice. m_state.variable = std::min(std::max(m_state.variable, -20.0f), 20.0f); } Float variable() const { return m_state.variable; } private: struct State { int iter = 0; Float firstMoment = 0; Float secondMoment = 0; Float variable = 0; Float batchAccumulation = 0; Float batchGradient = 0; } m_state; struct Hyperparameters { Float learningRate; int batchSize; Float epsilon; Float beta1; Float beta2; } m_hparams; }; enum class ESampleCombination { EDiscard, EDiscardWithAutomaticBudget, EInverseVariance, }; enum class EBsdfSamplingFractionLoss { ENone, EKL, EVariance, }; enum class ESpatialFilter { ENearest, EStochasticBox, EBox, }; enum class EDirectionalFilter { ENearest, EBox, }; enum class EDistribution { ERadiance, ESimple, EFull }; enum class EDIStrategy { ENoDI, EUnweightedDI, EWeightedDI }; class QuadTreeNode { public: QuadTreeNode() { m_children = {}; for (size_t i = 0; i < m_sum.size(); ++i) { m_sum[i].store(0, std::memory_order_relaxed); } } void setSum(int index, Float val) { m_sum[index].store(val, std::memory_order_relaxed); } Float sum(int index) const { return m_sum[index].load(std::memory_order_relaxed); } void copyFrom(const QuadTreeNode& arg) { for (int i = 0; i < 4; ++i) { setSum(i, arg.sum(i)); m_children[i] = arg.m_children[i]; } } QuadTreeNode(const QuadTreeNode& arg) { copyFrom(arg); } QuadTreeNode& operator=(const QuadTreeNode& arg) { copyFrom(arg); return *this; } void setChild(int idx, uint16_t val) { m_children[idx] = val; } uint16_t child(int idx) const { return m_children[idx]; } void setSum(Float val) { for (int i = 0; i < 4; ++i) { setSum(i, val); } } int childIndex(Point2& p) const { int res = 0; for (int i = 0; i < Point2::dim; ++i) { if (p[i] < 0.5f) { p[i] *= 2; } else { p[i] = (p[i] - 0.5f) * 2; res |= 1 << i; } } return res; } // Evaluates the directional irradiance *sum density* (i.e. sum / area) at a given location p. // To obtain radiance, the sum density (result of this function) must be divided // by the total statistical weight of the estimates that were summed up. Float eval(Point2& p, const std::vector<QuadTreeNode>& nodes) const { SAssert(p.x >= 0 && p.x <= 1 && p.y >= 0 && p.y <= 1); const int index = childIndex(p); if (isLeaf(index)) { return 4 * sum(index); } else { return 4 * nodes[child(index)].eval(p, nodes); } } Float pdf(Point2& p, const std::vector<QuadTreeNode>& nodes) const { SAssert(p.x >= 0 && p.x <= 1 && p.y >= 0 && p.y <= 1); const int index = childIndex(p); if (!(sum(index) > 0)) { return 0; } const Float factor = 4 * sum(index) / (sum(0) + sum(1) + sum(2) + sum(3)); if (isLeaf(index)) { return factor; } else { return factor * nodes[child(index)].pdf(p, nodes); } } int depthAt(Point2& p, const std::vector<QuadTreeNode>& nodes) const { SAssert(p.x >= 0 && p.x <= 1 && p.y >= 0 && p.y <= 1); const int index = childIndex(p); if (isLeaf(index)) { return 1; } else { return 1 + nodes[child(index)].depthAt(p, nodes); } } Point2 sample(Sampler* sampler, const std::vector<QuadTreeNode>& nodes) const { int index = 0; Float topLeft = sum(0); Float topRight = sum(1); Float partial = topLeft + sum(2); Float total = partial + topRight + sum(3); // Should only happen when there are numerical instabilities. if (!(total > 0.0f)) { return sampler->next2D(); } Float boundary = partial / total; Point2 origin = Point2{0.0f, 0.0f}; Float sample = sampler->next1D(); if (sample < boundary) { SAssert(partial > 0); sample /= boundary; boundary = topLeft / partial; } else { partial = total - partial; SAssert(partial > 0); origin.x = 0.5f; sample = (sample - boundary) / (1.0f - boundary); boundary = topRight / partial; index |= 1 << 0; } if (sample < boundary) { sample /= boundary; } else { origin.y = 0.5f; sample = (sample - boundary) / (1.0f - boundary); index |= 1 << 1; } if (isLeaf(index)) { return origin + 0.5f * sampler->next2D(); } else { return origin + 0.5f * nodes[child(index)].sample(sampler, nodes); } } void record(Point2& p, Float irradiance, std::vector<QuadTreeNode>& nodes) { SAssert(p.x >= 0 && p.x <= 1 && p.y >= 0 && p.y <= 1); int index = childIndex(p); if (isLeaf(index)) { addToAtomicFloat(m_sum[index], irradiance); } else { nodes[child(index)].record(p, irradiance, nodes); } } Float computeOverlappingArea(const Point2& min1, const Point2& max1, const Point2& min2, const Point2& max2) { Float lengths[2]; for (int i = 0; i < 2; ++i) { lengths[i] = std::max(std::min(max1[i], max2[i]) - std::max(min1[i], min2[i]), 0.0f); } return lengths[0] * lengths[1]; } void record(const Point2& origin, Float size, Point2 nodeOrigin, Float nodeSize, Float value, std::vector<QuadTreeNode>& nodes) { Float childSize = nodeSize / 2; for (int i = 0; i < 4; ++i) { Point2 childOrigin = nodeOrigin; if (i & 1) { childOrigin[0] += childSize; } if (i & 2) { childOrigin[1] += childSize; } Float w = computeOverlappingArea(origin, origin + Point2(size), childOrigin, childOrigin + Point2(childSize)); if (w > 0.0f) { if (isLeaf(i)) { addToAtomicFloat(m_sum[i], value * w); } else { nodes[child(i)].record(origin, size, childOrigin, childSize, value, nodes); } } } } bool isLeaf(int index) const { return child(index) == 0; } // Ensure that each quadtree node's sum of irradiance estimates // equals that of all its children. void build(std::vector<QuadTreeNode>& nodes, EDistribution distribution, Float parentSize = 1.f) { Float childSize = parentSize / 4.f; for (int i = 0; i < 4; ++i) { if (isLeaf(i)) { if (distribution == EDistribution::ESimple || distribution == EDistribution::EFull) { // @addition // our guiding distributions are based on the second moment and // therefore need a pointwise square-root operation setSum(i, std::sqrt(sum(i) * childSize)); } continue; } QuadTreeNode& c = nodes[child(i)]; // Recursively build each child such that their sum becomes valid... c.build(nodes, distribution, childSize); // ...then sum up the children's sums. Float sum = 0; for (int j = 0; j < 4; ++j) { sum += c.sum(j); } setSum(i, sum); } } private: std::array<std::atomic<Float>, 4> m_sum; std::array<uint16_t, 4> m_children; }; class DTree { public: DTree() { m_atomic.sum.store(0, std::memory_order_relaxed); m_maxDepth = 0; m_nodes.emplace_back(); m_nodes.front().setSum(0.0f); } QuadTreeNode& node(size_t i) { return m_nodes[i]; } const QuadTreeNode& node(size_t i) const { return m_nodes[i]; } Float mean() const { if (m_atomic.statisticalWeight == 0) { return 0; } const Float factor = 1 / (M_PI * 4 * m_atomic.statisticalWeight); return factor * m_atomic.sum; } void setMean(const Float& mean) { const Float factor = M_PI * 4 * m_atomic.statisticalWeight; m_atomic.sum.store(factor * mean, std::memory_order_relaxed); } void recordIrradiance(Point2 p, Float irradiance, Float statisticalWeight, EDirectionalFilter directionalFilter) { if (std::isfinite(statisticalWeight) && statisticalWeight > 0) { addToAtomicFloat(m_atomic.statisticalWeight, statisticalWeight); if (std::isfinite(irradiance) && irradiance > 0) { if (directionalFilter == EDirectionalFilter::ENearest) { m_nodes[0].record(p, irradiance * statisticalWeight, m_nodes); } else { int depth = depthAt(p); Float size = std::pow(0.5f, depth); Point2 origin = p; origin.x -= size / 2; origin.y -= size / 2; m_nodes[0].record(origin, size, Point2(0.0f), 1.0f, irradiance * statisticalWeight / (size * size), m_nodes); } } } } Float pdf(Point2 p) const { if (!(mean() > 0)) { return 1 / (4 * M_PI); } return m_nodes[0].pdf(p, m_nodes) / (4 * M_PI); } int depthAt(Point2 p) const { return m_nodes[0].depthAt(p, m_nodes); } int depth() const { return m_maxDepth; } Point2 sample(Sampler* sampler) const { if (!(mean() > 0)) { return sampler->next2D(); } Point2 res = m_nodes[0].sample(sampler, m_nodes); res.x = math::clamp(res.x, 0.0f, 1.0f); res.y = math::clamp(res.y, 0.0f, 1.0f); return res; } void setNumNodes(size_t numNodes) { m_nodes.resize(numNodes); } void resetSum() { for (auto& node : m_nodes) { node.setSum(0.f); } } size_t numNodes() const { return m_nodes.size(); } Float statisticalWeight() const { return m_atomic.statisticalWeight; } void setStatisticalWeight(Float statisticalWeight) { m_atomic.statisticalWeight = statisticalWeight; } void reset(const DTree& previousDTree, int newMaxDepth, Float subdivisionThreshold) { m_atomic = Atomic{}; m_maxDepth = 0; m_nodes.clear(); m_nodes.emplace_back(); struct StackNode { size_t nodeIndex; size_t otherNodeIndex; const DTree* otherDTree; int depth; }; std::stack<StackNode> nodeIndices; nodeIndices.push({0, 0, &previousDTree, 1}); const Float total = previousDTree.m_atomic.sum; // Create the topology of the new DTree to be the refined version // of the previous DTree. Subdivision is recursive if enough energy is there. while (!nodeIndices.empty()) { StackNode sNode = nodeIndices.top(); nodeIndices.pop(); m_maxDepth = std::max(m_maxDepth, sNode.depth); for (int i = 0; i < 4; ++i) { const QuadTreeNode& otherNode = sNode.otherDTree->m_nodes[sNode.otherNodeIndex]; const Float fraction = total > 0 ? (otherNode.sum(i) / total) : std::pow(0.25f, sNode.depth); SAssert(fraction <= 1.0f + Epsilon); if (sNode.depth < newMaxDepth && fraction > subdivisionThreshold) { if (!otherNode.isLeaf(i)) { SAssert(sNode.otherDTree == &previousDTree); nodeIndices.push({m_nodes.size(), otherNode.child(i), &previousDTree, sNode.depth + 1}); } else { nodeIndices.push({m_nodes.size(), m_nodes.size(), this, sNode.depth + 1}); } m_nodes[sNode.nodeIndex].setChild(i, static_cast<uint16_t>(m_nodes.size())); m_nodes.emplace_back(); m_nodes.back().setSum(otherNode.sum(i) / 4); if (m_nodes.size() > std::numeric_limits<uint16_t>::max()) { SLog(EWarn, "DTreeWrapper hit maximum children count."); nodeIndices = std::stack<StackNode>(); break; } } } } // Uncomment once memory becomes an issue. //m_nodes.shrink_to_fit(); for (auto& node : m_nodes) { node.setSum(0); } } size_t approxMemoryFootprint() const { return m_nodes.capacity() * sizeof(QuadTreeNode) + sizeof(*this); } void build(EDistribution distribution) { auto& root = m_nodes[0]; // Build the quadtree recursively, starting from its root. root.build(m_nodes, distribution); // Ensure that the overall sum of irradiance estimates equals // the sum of irradiance estimates found in the quadtree. Float sum = 0; for (int i = 0; i < 4; ++i) { sum += root.sum(i); } m_atomic.sum.store(sum); } private: std::vector<QuadTreeNode> m_nodes; struct Atomic { Atomic() { sum.store(0, std::memory_order_relaxed); statisticalWeight.store(0, std::memory_order_relaxed); } Atomic(const Atomic& arg) { *this = arg; } Atomic& operator=(const Atomic& arg) { sum.store(arg.sum.load(std::memory_order_relaxed), std::memory_order_relaxed); statisticalWeight.store(arg.statisticalWeight.load(std::memory_order_relaxed), std::memory_order_relaxed); return *this; } std::atomic<Float> sum; std::atomic<Float> statisticalWeight; } m_atomic; public: int m_maxDepth; }; struct DTreeRecord { Vector d; Float radiance, product; Float woPdf, bsdfPdf, dTreePdf; Float statisticalWeight; bool isDelta; }; struct DTreeWrapper { public: DTreeWrapper() { } void record(const DTreeRecord& rec, EDirectionalFilter directionalFilter, EBsdfSamplingFractionLoss bsdfSamplingFractionLoss) { if (!rec.isDelta) { Float irradiance = rec.radiance / rec.woPdf; building.recordIrradiance(dirToCanonical(rec.d), irradiance, rec.statisticalWeight, directionalFilter); } if (bsdfSamplingFractionLoss != EBsdfSamplingFractionLoss::ENone && rec.product > 0) { optimizeBsdfSamplingFraction(rec, bsdfSamplingFractionLoss == EBsdfSamplingFractionLoss::EKL ? 1.0f : 2.0f); } } static Vector canonicalToDir(Point2 p) { const Float cosTheta = 2 * p.x - 1; const Float phi = 2 * M_PI * p.y; const Float sinTheta = sqrt(1 - cosTheta * cosTheta); Float sinPhi, cosPhi; math::sincos(phi, &sinPhi, &cosPhi); return {sinTheta * cosPhi, sinTheta * sinPhi, cosTheta}; } static Point2 dirToCanonical(const Vector& d) { if (!std::isfinite(d.x) || !std::isfinite(d.y) || !std::isfinite(d.z)) { return {0, 0}; } const Float cosTheta = std::min(std::max(d.z, -1.0f), 1.0f); Float phi = std::atan2(d.y, d.x); while (phi < 0) phi += 2.0 * M_PI; return {(cosTheta + 1) / 2, phi / (2 * M_PI)}; } void build(EDistribution distribution) { building.build(distribution); sampling = building; } void reset(int maxDepth, Float subdivisionThreshold) { building.reset(sampling, maxDepth, subdivisionThreshold); } Vector sample(Sampler* sampler) const { return canonicalToDir(sampling.sample(sampler)); } Float pdf(const Vector& dir) const { return sampling.pdf(dirToCanonical(dir)); } Float diff(const DTreeWrapper& other) const { return 0.0f; } int depth() const { return sampling.depth(); } size_t numNodes() const { return sampling.numNodes(); } Float meanRadiance() const { return sampling.mean(); } Float statisticalWeight() const { return sampling.statisticalWeight(); } Float statisticalWeightBuilding() const { return building.statisticalWeight(); } void setStatisticalWeightBuilding(Float statisticalWeight) { building.setStatisticalWeight(statisticalWeight); } size_t approxMemoryFootprint() const { return building.approxMemoryFootprint() + sampling.approxMemoryFootprint(); } inline Float bsdfSamplingFraction(Float variable) const { return logistic(variable); } inline Float dBsdfSamplingFraction_dVariable(Float variable) const { Float fraction = bsdfSamplingFraction(variable); return fraction * (1 - fraction); } inline Float bsdfSamplingFraction() const { return bsdfSamplingFraction(bsdfSamplingFractionOptimizer.variable()); } void optimizeBsdfSamplingFraction(const DTreeRecord& rec, Float ratioPower) { m_lock.lock(); // GRADIENT COMPUTATION Float variable = bsdfSamplingFractionOptimizer.variable(); Float samplingFraction = bsdfSamplingFraction(variable); // Loss gradient w.r.t. sampling fraction Float mixPdf = samplingFraction * rec.bsdfPdf + (1 - samplingFraction) * rec.dTreePdf; Float ratio = std::pow(rec.product / mixPdf, ratioPower); Float dLoss_dSamplingFraction = -ratio / rec.woPdf * (rec.bsdfPdf - rec.dTreePdf); // Chain rule to get loss gradient w.r.t. trainable variable Float dLoss_dVariable = dLoss_dSamplingFraction * dBsdfSamplingFraction_dVariable(variable); // We want some regularization such that our parameter does not become too big. // We use l2 regularization, resulting in the following linear gradient. Float l2RegGradient = 0.01f * variable; Float lossGradient = l2RegGradient + dLoss_dVariable; // ADAM GRADIENT DESCENT bsdfSamplingFractionOptimizer.append(lossGradient, rec.statisticalWeight); m_lock.unlock(); } void read(BlobReader& blob) { float mean; float statisticalWeight; uint64_t numNodes; int mCount; float zero = 0; blob >> (float&)mean >> (float&)statisticalWeight >> (uint64_t&)numNodes >> (int&)sampling.m_maxDepth >> (float&)zero >> (float&)zero >> (int&)mCount ; Spectrum m; for (int i = 0; i < SPECTRUM_SAMPLES; ++i) blob >> (float&)m[i]; sampling.setNumNodes(numNodes); sampling.setStatisticalWeight(statisticalWeight); sampling.setMean(mean); //sampling.setMeasurementCount(mCount); //sampling.setMeasurement(m); for (size_t i = 0; i < sampling.numNodes(); ++i) { auto& node = sampling.node(i); for (int j = 0; j < 4; ++j) { float mean; uint16_t child; blob >> (float&)mean; mean = std::max(mean, 0.f); //SAssert(mean >= 0.0f); blob >> (uint16_t&)child; node.setSum(j, mean); node.setChild(j, child); } } building = sampling; building.resetSum(); } void dump(BlobWriter& blob) const { blob << (float)sampling.mean() << (float)sampling.statisticalWeight() << (uint64_t)sampling.numNodes() << (int)sampling.m_maxDepth << (float)bsdfSamplingFractionOptimizer.variable() << (float)0 << (int)0 ; Spectrum m { 0.f }; for (int i = 0; i < SPECTRUM_SAMPLES; ++i) blob << (float)m[i]; for (size_t i = 0; i < sampling.numNodes(); ++i) { const auto& node = sampling.node(i); for (int j = 0; j < 4; ++j) { blob << (float)node.sum(j) << (uint16_t)node.child(j); } } } private: DTree building; DTree sampling; AdamOptimizer bsdfSamplingFractionOptimizer{0.01f}; class SpinLock { public: SpinLock() { m_mutex.clear(std::memory_order_release); } SpinLock(const SpinLock& other) { m_mutex.clear(std::memory_order_release); } SpinLock& operator=(const SpinLock& other) { return *this; } void lock() { while (m_mutex.test_and_set(std::memory_order_acquire)) { } } void unlock() { m_mutex.clear(std::memory_order_release); } private: std::atomic_flag m_mutex; } m_lock; }; struct STreeNode { STreeNode() { children = {}; isLeaf = true; axis = 0; } int childIndex(Point& p) const { if (p[axis] < 0.5f) { p[axis] *= 2; return 0; } else { p[axis] = (p[axis] - 0.5f) * 2; return 1; } } int nodeIndex(Point& p) const { return children[childIndex(p)]; } DTreeWrapper* dTreeWrapper(Point& p, Vector& size, std::vector<STreeNode>& nodes) { SAssert(p[axis] >= 0 && p[axis] <= 1); if (isLeaf) { return &dTree; } else { size[axis] /= 2; return nodes[nodeIndex(p)].dTreeWrapper(p, size, nodes); } } const DTreeWrapper* dTreeWrapper() const { return &dTree; } int depth(Point& p, const std::vector<STreeNode>& nodes) const { SAssert(p[axis] >= 0 && p[axis] <= 1); if (isLeaf) { return 1; } else { return 1 + nodes[nodeIndex(p)].depth(p, nodes); } } int depth(const std::vector<STreeNode>& nodes) const { int result = 1; if (!isLeaf) { for (auto c : children) { result = std::max(result, 1 + nodes[c].depth(nodes)); } } return result; } void forEachLeaf( std::function<void(const DTreeWrapper*, const Point&, const Vector&)> func, Point p, Vector size, const std::vector<STreeNode>& nodes) const { if (isLeaf) { func(&dTree, p, size); } else { size[axis] /= 2; for (int i = 0; i < 2; ++i) { Point childP = p; if (i == 1) { childP[axis] += size[axis]; } nodes[children[i]].forEachLeaf(func, childP, size, nodes); } } } Float computeOverlappingVolume(const Point& min1, const Point& max1, const Point& min2, const Point& max2) { Float lengths[3]; for (int i = 0; i < 3; ++i) { lengths[i] = std::max(std::min(max1[i], max2[i]) - std::max(min1[i], min2[i]), 0.0f); } return lengths[0] * lengths[1] * lengths[2]; } void record(const Point& min1, const Point& max1, Point min2, Vector size2, const DTreeRecord& rec, EDirectionalFilter directionalFilter, EBsdfSamplingFractionLoss bsdfSamplingFractionLoss, std::vector<STreeNode>& nodes) { Float w = computeOverlappingVolume(min1, max1, min2, min2 + size2); if (w > 0) { if (isLeaf) { dTree.record({ rec.d, rec.radiance, rec.product, rec.woPdf, rec.bsdfPdf, rec.dTreePdf, rec.statisticalWeight * w, rec.isDelta }, directionalFilter, bsdfSamplingFractionLoss); } else { size2[axis] /= 2; for (int i = 0; i < 2; ++i) { if (i & 1) { min2[axis] += size2[axis]; } nodes[children[i]].record(min1, max1, min2, size2, rec, directionalFilter, bsdfSamplingFractionLoss, nodes); } } } } void read(BlobReader& blob) { blob >> (bool&)isLeaf >> (int&)axis >> (uint32_t&)children[0] >> (uint32_t&)children[1]; if (isLeaf) dTree.read(blob); } void dump(BlobWriter& blob) const { blob << (bool)isLeaf << (int)axis << (uint32_t)children[0] << (uint32_t)children[1]; if (isLeaf) dTree.dump(blob); } bool isLeaf; DTreeWrapper dTree; int axis; std::array<uint32_t, 2> children; }; class STree { public: STree(const AABB& aabb) { clear(); m_aabb = aabb; // Enlarge AABB to turn it into a cube. This has the effect // of nicer hierarchical subdivisions. Vector size = m_aabb.max - m_aabb.min; Float maxSize = std::max(std::max(size.x, size.y), size.z); m_aabb.max = m_aabb.min + Vector(maxSize); } void clear() { m_nodes.clear(); m_nodes.emplace_back(); } void subdivideAll() { int nNodes = (int)m_nodes.size(); for (int i = 0; i < nNodes; ++i) { if (m_nodes[i].isLeaf) { subdivide(i, m_nodes); } } } void subdivide(int nodeIdx, std::vector<STreeNode>& nodes) { // Add 2 child nodes nodes.resize(nodes.size() + 2); if (nodes.size() > std::numeric_limits<uint32_t>::max()) { SLog(EWarn, "DTreeWrapper hit maximum children count."); return; } STreeNode& cur = nodes[nodeIdx]; for (int i = 0; i < 2; ++i) { uint32_t idx = (uint32_t)nodes.size() - 2 + i; cur.children[i] = idx; nodes[idx].axis = (cur.axis + 1) % 3; nodes[idx].dTree = cur.dTree; nodes[idx].dTree.setStatisticalWeightBuilding(nodes[idx].dTree.statisticalWeightBuilding() / 2); } cur.isLeaf = false; cur.dTree = {}; // Reset to an empty dtree to save memory. } DTreeWrapper* dTreeWrapper(Point p, Vector& size) { size = m_aabb.getExtents(); p = Point(p - m_aabb.min); p.x /= size.x; p.y /= size.y; p.z /= size.z; return m_nodes[0].dTreeWrapper(p, size, m_nodes); } DTreeWrapper* dTreeWrapper(Point p) { Vector size; return dTreeWrapper(p, size); } void forEachDTreeWrapperConst(std::function<void(const DTreeWrapper*)> func) const { for (auto& node : m_nodes) { if (node.isLeaf) { func(&node.dTree); } } } void forEachDTreeWrapperConstP(std::function<void(const DTreeWrapper*, const Point&, const Vector&)> func) const { m_nodes[0].forEachLeaf(func, m_aabb.min, m_aabb.max - m_aabb.min, m_nodes); } void forEachDTreeWrapperParallel(std::function<void(DTreeWrapper*)> func) { int nDTreeWrappers = static_cast<int>(m_nodes.size()); #pragma omp parallel for for (int i = 0; i < nDTreeWrappers; ++i) { if (m_nodes[i].isLeaf) { func(&m_nodes[i].dTree); } } } void record(const Point& p, const Vector& dTreeVoxelSize, DTreeRecord rec, EDirectionalFilter directionalFilter, EBsdfSamplingFractionLoss bsdfSamplingFractionLoss) { Float volume = 1; for (int i = 0; i < 3; ++i) { volume *= dTreeVoxelSize[i]; } rec.statisticalWeight /= volume; m_nodes[0].record(p - dTreeVoxelSize * 0.5f, p + dTreeVoxelSize * 0.5f, m_aabb.min, m_aabb.getExtents(), rec, directionalFilter, bsdfSamplingFractionLoss, m_nodes); } void read(BlobReader& blob) { size_t numNodes; blob >> (size_t&)numNodes >> (float&)m_aabb.min.x >> (float&)m_aabb.min.y >> (float&)m_aabb.min.z >> (float&)m_aabb.max.x >> (float&)m_aabb.max.y >> (float&)m_aabb.max.z; m_nodes.resize(numNodes); for (size_t i = 0; i < m_nodes.size(); ++i) { auto& node = m_nodes[i]; node.read(blob); } } void dump(BlobWriter& blob) const { blob << (size_t)m_nodes.size() << (float)m_aabb.min.x << (float)m_aabb.min.y << (float)m_aabb.min.z << (float)m_aabb.max.x << (float)m_aabb.max.y << (float)m_aabb.max.z; for (size_t i = 0; i < m_nodes.size(); ++i) { auto& node = m_nodes[i]; node.dump(blob); } } bool shallSplit(const STreeNode& node, int depth, size_t samplesRequired) { return m_nodes.size() < std::numeric_limits<uint32_t>::max() - 1 && node.dTree.statisticalWeightBuilding() > samplesRequired; } void refine(size_t sTreeThreshold, int maxMB) { if (maxMB >= 0) { size_t approxMemoryFootprint = 0; for (const auto& node : m_nodes) { approxMemoryFootprint += node.dTreeWrapper()->approxMemoryFootprint(); } if (approxMemoryFootprint / 1000000 >= (size_t)maxMB) { return; } } struct StackNode { size_t index; int depth; }; std::stack<StackNode> nodeIndices; nodeIndices.push({0, 1}); while (!nodeIndices.empty()) { StackNode sNode = nodeIndices.top(); nodeIndices.pop(); // Subdivide if needed and leaf if (m_nodes[sNode.index].isLeaf) { if (shallSplit(m_nodes[sNode.index], sNode.depth, sTreeThreshold)) { subdivide((int)sNode.index, m_nodes); } } // Add children to stack if we're not if (!m_nodes[sNode.index].isLeaf) { const STreeNode& node = m_nodes[sNode.index]; for (int i = 0; i < 2; ++i) { nodeIndices.push({node.children[i], sNode.depth + 1}); } } } // Uncomment once memory becomes an issue. //m_nodes.shrink_to_fit(); } const AABB& aabb() const { return m_aabb; } private: std::vector<STreeNode> m_nodes; AABB m_aabb; }; static StatsCounter avgPathLength("Guided path tracer", "Average path length", EAverage); class GuidedPathTracer : public MonteCarloIntegrator { public: GuidedPathTracer(const Properties &props) : MonteCarloIntegrator(props) { for (const auto& name : props.getPropertyNames()) { Log(EInfo, "'%s': '%s'", name.c_str(), props.getAsString(name).c_str()); } if (!Thread::getThread()->getLogger()->readLog(m_configLog)) Log(EInfo, "could not retrieve log"); m_neeStr = props.getString("nee", "always"); if (m_neeStr == "never") { m_nee = ENever; } else if (m_neeStr == "kickstart") { m_nee = EKickstart; } else if (m_neeStr == "always") { m_nee = EAlways; } else { Assert(false); } m_sampleCombinationStr = props.getString("sampleCombination", "discard"); if (m_sampleCombinationStr == "discard") { m_sampleCombination = ESampleCombination::EDiscard; } else if (m_sampleCombinationStr == "automatic") { m_sampleCombination = ESampleCombination::EDiscardWithAutomaticBudget; } else if (m_sampleCombinationStr == "inversevar") { m_sampleCombination = ESampleCombination::EInverseVariance; } else { Assert(false); } m_spatialFilterStr = props.getString("spatialFilter", "box"); if (m_spatialFilterStr == "nearest") { m_spatialFilter = ESpatialFilter::ENearest; } else if (m_spatialFilterStr == "stochastic") { m_spatialFilter = ESpatialFilter::EStochasticBox; } else if (m_spatialFilterStr == "box") { m_spatialFilter = ESpatialFilter::EBox; } else { Assert(false); } m_directionalFilterStr = props.getString("directionalFilter", "box"); if (m_directionalFilterStr == "nearest") { m_directionalFilter = EDirectionalFilter::ENearest; } else if (m_directionalFilterStr == "box") { m_directionalFilter = EDirectionalFilter::EBox; } else { Assert(false); } m_distributionStr = props.getString("distribution", "radiance"); if (m_distributionStr == "radiance") { m_distribution = EDistribution::ERadiance; } else if (m_distributionStr == "simple") { m_distribution = EDistribution::ESimple; } else if (m_distributionStr == "full") { m_distribution = EDistribution::EFull; } else { Assert(false); } auto diStr = props.getString("diStrategy", "no"); if (diStr == "no" ) m_diStrategy = EDIStrategy::ENoDI; else if (diStr == "weighted" ) m_diStrategy = EDIStrategy::EWeightedDI; else if (diStr == "unweighted") m_diStrategy = EDIStrategy::EUnweightedDI; else Assert(false); m_bsdfSamplingFractionLossStr = props.getString("bsdfSamplingFractionLoss", "none"); if (m_bsdfSamplingFractionLossStr == "none") { m_bsdfSamplingFractionLoss = EBsdfSamplingFractionLoss::ENone; } else if (m_bsdfSamplingFractionLossStr == "kl") { m_bsdfSamplingFractionLoss = EBsdfSamplingFractionLoss::EKL; } else if (m_bsdfSamplingFractionLossStr == "var") { m_bsdfSamplingFractionLoss = EBsdfSamplingFractionLoss::EVariance; } else { Assert(false); } m_sdTreeMaxMemory = props.getInteger("sdTreeMaxMemory", -1); m_sTreeThreshold = props.getInteger("sTreeThreshold", 2000); m_dTreeThreshold = props.getFloat("dTreeThreshold", 0.005f); m_bsdfSamplingFraction = props.getFloat("bsdfSamplingFraction", 0.5f); m_sppPerPass = props.getInteger("sppPerPass", 1); m_budgetStr = props.getString("budgetType", "seconds"); if (m_budgetStr == "spp") { m_budgetType = ESpp; } else if (m_budgetStr == "seconds") { m_budgetType = ESeconds; } else { Assert(false); } m_budget = props.getFloat("budget", 300.0f); m_dumpSDTree = props.getBoolean("dumpSDTree", false); m_trainingIterations = props.getInteger("trainingIterations", -1); } ref<BlockedRenderProcess> renderPass(Scene *scene, RenderQueue *queue, const RenderJob *job, int sceneResID, int sensorResID, int samplerResID, int integratorResID) { /* This is a sampling-based integrator - parallelize */ ref<BlockedRenderProcess> proc = new BlockedRenderProcess(job, queue, scene->getBlockSize()); proc->disableProgress(); proc->bindResource("integrator", integratorResID); proc->bindResource("scene", sceneResID); proc->bindResource("sensor", sensorResID); proc->bindResource("sampler", samplerResID); scene->bindUsedResources(proc); bindUsedResources(proc); return proc; } void resetSDTree() { Log(EInfo, "Resetting distributions for sampling."); m_sdTree->refine((size_t)(std::sqrt(std::pow(2, m_iter) * m_sppPerPass / 4) * m_sTreeThreshold), m_sdTreeMaxMemory); m_sdTree->forEachDTreeWrapperParallel([this](DTreeWrapper* dTree) { dTree->reset(20, m_dTreeThreshold); }); } void buildSDTree(bool doBuild = true) { if (doBuild) { Log(EInfo, "Building distributions for sampling."); // Build distributions m_sdTree->forEachDTreeWrapperParallel([this](DTreeWrapper* dTree) { dTree->build(m_distribution); }); } // Gather statistics int maxDepth = 0; int minDepth = std::numeric_limits<int>::max(); Float avgDepth = 0; Float maxAvgRadiance = 0; Float minAvgRadiance = std::numeric_limits<Float>::max(); Float avgAvgRadiance = 0; size_t maxNodes = 0; size_t minNodes = std::numeric_limits<size_t>::max(); Float avgNodes = 0; Float maxStatisticalWeight = 0; Float minStatisticalWeight = std::numeric_limits<Float>::max(); Float avgStatisticalWeight = 0; int nPoints = 0; int nPointsNodes = 0; m_sdTree->forEachDTreeWrapperConst([&](const DTreeWrapper* dTree) { const int depth = dTree->depth(); maxDepth = std::max(maxDepth, depth); minDepth = std::min(minDepth, depth); avgDepth += depth; const Float avgRadiance = dTree->meanRadiance(); maxAvgRadiance = std::max(maxAvgRadiance, avgRadiance); minAvgRadiance = std::min(minAvgRadiance, avgRadiance); avgAvgRadiance += avgRadiance; if (dTree->numNodes() > 1) { const size_t nodes = dTree->numNodes(); maxNodes = std::max(maxNodes, nodes); minNodes = std::min(minNodes, nodes); avgNodes += nodes; ++nPointsNodes; } const Float statisticalWeight = dTree->statisticalWeight(); maxStatisticalWeight = std::max(maxStatisticalWeight, statisticalWeight); minStatisticalWeight = std::min(minStatisticalWeight, statisticalWeight); avgStatisticalWeight += statisticalWeight; ++nPoints; }); if (nPoints > 0) { avgDepth /= nPoints; avgAvgRadiance /= nPoints; if (nPointsNodes > 0) { avgNodes /= nPointsNodes; } avgStatisticalWeight /= nPoints; } Log(EInfo, "Distribution statistics:\n" " Depth = [%d, %f, %d]\n" " Mean radiance = [%f, %f, %f]\n" " Node count = [" SIZE_T_FMT ", %f, " SIZE_T_FMT "]\n" " Stat. weight = [%f, %f, %f]\n", minDepth, avgDepth, maxDepth, minAvgRadiance, avgAvgRadiance, maxAvgRadiance, minNodes, avgNodes, maxNodes, minStatisticalWeight, avgStatisticalWeight, maxStatisticalWeight ); m_isBuilt = true; } bool restoreSDTree(Scene* scene) { fs::path path = scene->getDestinationFile(); path = path.parent_path() / (path.leaf().string() + ".sdt"); BlobReader blob(path.string()); blob.readString(); if (!blob.isValid()) { return false; } Matrix4x4 cameraMatrix; for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { blob >> (float&)cameraMatrix(i, j); } } m_sdTree->read(blob); buildSDTree(false); return true; } void dumpSDTree(Scene* scene, ref<Sensor> sensor) { std::ostringstream extension; extension << "-" << std::setfill('0') << std::setw(2) << m_iter << ".sdt"; fs::path path = scene->getDestinationFile(); path = path.parent_path() / (path.leaf().string() + extension.str()); auto cameraMatrix = sensor->getWorldTransform()->eval(0).getMatrix(); BlobWriter blob(path.string()); blob.writeString(m_configLog); for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { blob << (float)cameraMatrix(i, j); } } m_sdTree->dump(blob); } bool performRenderPasses(Float& variance, int numPasses, Scene *scene, RenderQueue *queue, const RenderJob *job, int sceneResID, int sensorResID, int samplerResID, int integratorResID) { ref<Scheduler> sched = Scheduler::getInstance(); ref<Sensor> sensor = static_cast<Sensor *>(sched->getResource(sensorResID)); ref<Film> film = sensor->getFilm(); m_image->clear(); m_squaredImage->clear(); size_t totalBlocks = 0; Log(EInfo, "Rendering %d render passes.", numPasses); auto start = std::chrono::steady_clock::now(); for (int i = 0; i < numPasses; ++i) { ref<BlockedRenderProcess> process = renderPass(scene, queue, job, sceneResID, sensorResID, samplerResID, integratorResID); m_renderProcesses.push_back(process); totalBlocks += process->totalBlocks(); } bool result = true; int passesRenderedLocal = 0; static const size_t processBatchSize = 128; for (size_t i = 0; i < m_renderProcesses.size(); i += processBatchSize) { const size_t start = i; const size_t end = std::min(i + processBatchSize, m_renderProcesses.size()); for (size_t j = start; j < end; ++j) { sched->schedule(m_renderProcesses[j]); } for (size_t j = start; j < end; ++j) { auto& process = m_renderProcesses[j]; sched->wait(process); ++m_passesRendered; ++m_passesRenderedThisIter; ++passesRenderedLocal; int progress = 0; bool shouldAbort; switch (m_budgetType) { case ESpp: progress = m_passesRendered; shouldAbort = false; break; case ESeconds: progress = (int)computeElapsedSeconds(m_startTime); shouldAbort = progress > m_budget; break; default: Assert(false); break; } m_progress->update(progress); if (process->getReturnStatus() != ParallelProcess::ESuccess) { result = false; shouldAbort = true; } if (shouldAbort) { goto l_abort; } } } l_abort: for (auto& process : m_renderProcesses) { sched->cancel(process); } m_renderProcesses.clear(); variance = 0; Bitmap* squaredImage = m_squaredImage->getBitmap(); Bitmap* image = m_image->getBitmap(); if (m_sampleCombination == ESampleCombination::EInverseVariance) { // Record all previously rendered iterations such that later on all iterations can be // combined by weighting them by their estimated inverse pixel variance. m_images.push_back(image->clone()); } // @addition calculate ad-hoc pixel estimate using iterated box filters // results can be slightly enhanced with a properly denoised pixel estimate, // which is, however, orthogonal to our work if (m_distribution == EDistribution::EFull && !m_isFinalIter) { Vector2i size = image->getSize(); m_pixelEstimate = image->clone(); int blackPixels = 0; auto data = static_cast<Float *>(m_pixelEstimate->getData()); int fpp = int(m_pixelEstimate->getBytesPerPixel() / sizeof(Float)); // floats per pixel for (int i = 0, j = size.x*size.y; i < j; ++i) { int isBlack = true; for (int chan = 0; chan < SPECTRUM_SAMPLES; ++chan) isBlack &= data[chan + i*fpp] == 0.f; blackPixels += isBlack; } Float blackDensity = 1.f / (std::sqrt(1.f - blackPixels / Float(size.x*size.y)) + 1e-3); const int FILTER_WIDTH = std::max(std::min(int(3 * blackDensity), std::min(size.x, size.y)-1), 1); const int FILTER_ITERATIONS = 3; //SLog(EInfo, "filter: %d x%d", FILTER_WIDTH, FILTER_ITERATIONS); Float *stack = new Float[FILTER_WIDTH]; auto boxFilter = [=](Float *data, int stride, int n) { assert(n > FILTER_WIDTH); double avg = FILTER_WIDTH * data[0]; for (int i = 0; i < FILTER_WIDTH; ++i) { stack[i] = data[0]; avg += data[i * stride]; } for (int i = 0; i < n; ++i) { avg += data[std::min(i + FILTER_WIDTH, n - 1) * stride]; Float newVal = avg; avg -= stack[i % FILTER_WIDTH]; stack[i % FILTER_WIDTH] = data[i * stride]; data[i * stride] = newVal; } }; for (int i = 0, j = size.x*size.y; i < j; ++i) { Float &weight = data[SPECTRUM_SAMPLES+1 + i*fpp]; if (weight > 0.f) for (int chan = 0; chan < SPECTRUM_SAMPLES; ++chan) data[chan + i*fpp] /= weight; weight = 1.f; } for (int chan = 0; chan < SPECTRUM_SAMPLES; ++chan) { for (int iter = 0; iter < FILTER_ITERATIONS; ++iter) { for (int x = 0; x < size.x; ++x) boxFilter(data + chan + x*fpp, size.x*fpp, size.y); for (int y = 0; y < size.y; ++y) boxFilter(data + chan + y*size.x*fpp, fpp, size.x); } for (int i = 0, j = size.x * size.y; i < j; ++i) { Float norm = 1.f / std::pow(2 * FILTER_WIDTH + 1, 2*FILTER_ITERATIONS); data[chan + i*fpp] *= norm; // apply offset to avoid numerical instabilities data[chan + i*fpp] += 1e-3; } } delete[] stack; } m_varianceBuffer->clear(); int N = passesRenderedLocal * m_sppPerPass; Vector2i size = squaredImage->getSize(); for (int x = 0; x < size.x; ++x) for (int y = 0; y < size.y; ++y) { Point2i pos = Point2i(x, y); Spectrum pixel = image->getPixel(pos); Spectrum localVar = squaredImage->getPixel(pos) - pixel * pixel / (Float)N; image->setPixel(pos, localVar); // The local variance is clamped such that fireflies don't cause crazily unstable estimates. variance += std::min(localVar.getLuminance(), 10000.0f); } variance /= (Float)size.x * size.y * (N - 1); m_varianceBuffer->put(m_image); if (m_sampleCombination == ESampleCombination::EInverseVariance) { // Record estimated mean pixel variance for later use in weighting of all images. m_variances.push_back(variance); } Float seconds = computeElapsedSeconds(start); const Float ttuv = seconds * variance; const Float stuv = passesRenderedLocal * m_sppPerPass * variance; Log(EInfo, "%.2f seconds, Total passes: %d, Var: %f, TTUV: %f, STUV: %f.", seconds, m_passesRendered, variance, ttuv, stuv); return result; } bool doNeeWithSpp(int spp) { switch (m_nee) { case ENever: return false; case EKickstart: return spp < 128; default: return true; } } bool renderSPP(Scene *scene, RenderQueue *queue, const RenderJob *job, int sceneResID, int sensorResID, int samplerResID, int integratorResID) { ref<Scheduler> sched = Scheduler::getInstance(); size_t sampleCount = (size_t)m_budget; ref<Sensor> sensor = static_cast<Sensor *>(sched->getResource(sensorResID)); ref<Film> film = sensor->getFilm(); int nPasses = (int)std::ceil(sampleCount / (Float)m_sppPerPass); sampleCount = m_sppPerPass * nPasses; bool result = true; Float currentVarAtEnd = std::numeric_limits<Float>::infinity(); if (restoreSDTree(scene)) { Log(EInfo, "RESTORED SD TREE"); Float variance; film->clear(); m_isFinalIter = true; m_doNee = doNeeWithSpp(256); m_progress = std::unique_ptr<ProgressReporter>(new ProgressReporter("Rendering", m_budget, job)); m_sppPerPass = 1; if (!performRenderPasses(variance, m_budget, scene, queue, job, sceneResID, sensorResID, samplerResID, integratorResID)) { return false; } return true; } m_progress = std::unique_ptr<ProgressReporter>(new ProgressReporter("Rendering", nPasses, job)); while (result && m_passesRendered < nPasses) { const int sppRendered = m_passesRendered * m_sppPerPass; m_doNee = doNeeWithSpp(sppRendered); int remainingPasses = nPasses - m_passesRendered; int passesThisIteration = std::min(remainingPasses, 1 << m_iter); // If the next iteration does not manage to double the number of passes once more // then it would be unwise to throw away the current iteration. Instead, extend // the current iteration to the end. // This condition can also be interpreted as: the last iteration must always use // at _least_ half the total sample budget. //if (remainingPasses - passesThisIteration < 2 * passesThisIteration) { // passesThisIteration = remainingPasses; //} Log(EInfo, "ITERATION %d, %d passes", m_iter, passesThisIteration); m_isFinalIter = passesThisIteration >= remainingPasses; film->clear(); resetSDTree(); Float variance; if (!performRenderPasses(variance, passesThisIteration, scene, queue, job, sceneResID, sensorResID, samplerResID, integratorResID)) { result = false; break; } const Float lastVarAtEnd = currentVarAtEnd; currentVarAtEnd = passesThisIteration * variance / remainingPasses; Log(EInfo, "Extrapolated var:\n" " Last: %f\n" " Current: %f\n", lastVarAtEnd, currentVarAtEnd); remainingPasses -= passesThisIteration; if (m_sampleCombination == ESampleCombination::EDiscardWithAutomaticBudget && remainingPasses > 0 && ( // if there is any time remaining we want to keep going if // either will have less time next iter remainingPasses < passesThisIteration || // or, according to the convergence behavior, we're better off if we keep going // (we only trust the variance if we drew enough samples for it to be a reliable estimate, // captured by an arbitraty threshold). (sppRendered > 256 && currentVarAtEnd > lastVarAtEnd) )) { Log(EInfo, "FINAL %d passes", remainingPasses); m_isFinalIter = true; if (!performRenderPasses(variance, remainingPasses, scene, queue, job, sceneResID, sensorResID, samplerResID, integratorResID)) { result = false; break; } } buildSDTree(); if (m_dumpSDTree) { dumpSDTree(scene, sensor); } ++m_iter; m_passesRenderedThisIter = 0; } return result; } static Float computeElapsedSeconds(std::chrono::steady_clock::time_point start) { auto current = std::chrono::steady_clock::now(); auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(current - start); return (Float)ms.count() / 1000; } bool renderTime(Scene *scene, RenderQueue *queue, const RenderJob *job, int sceneResID, int sensorResID, int samplerResID, int integratorResID) { ref<Scheduler> sched = Scheduler::getInstance(); ref<Sensor> sensor = static_cast<Sensor *>(sched->getResource(sensorResID)); ref<Film> film = sensor->getFilm(); const Float nSeconds = m_budget; bool result = true; Float currentVarAtEnd = std::numeric_limits<Float>::infinity(); m_progress = std::unique_ptr<ProgressReporter>(new ProgressReporter("Rendering", (int)nSeconds, job)); Float elapsedSeconds = 0; while (result && elapsedSeconds < nSeconds) { Float variance; const int sppRendered = m_passesRendered * m_sppPerPass; m_doNee = doNeeWithSpp(sppRendered); Float remainingTime = nSeconds - elapsedSeconds; const int passesThisIteration = 1 << m_iter; Log(EInfo, "ITERATION %d, %d passes", m_iter, passesThisIteration); const auto startIter = std::chrono::steady_clock::now(); film->clear(); resetSDTree(); if ( (elapsedSeconds / Float(nSeconds) >= 0.15 && m_trainingIterations == -1) || m_trainingIterations == m_iter ) { Log(EInfo, "FINAL %f seconds", remainingTime); m_isFinalIter = true; Float secsPerPass; int passes = passesThisIteration; do { Float elapsedBefore = elapsedSeconds; if (!performRenderPasses(variance, passes, scene, queue, job, sceneResID, sensorResID, samplerResID, integratorResID)) { result = false; break; } elapsedSeconds = computeElapsedSeconds(m_startTime); secsPerPass = (elapsedSeconds - elapsedBefore) / passes; passes = std::max(1, std::min(128, int((nSeconds - elapsedSeconds) / secsPerPass))); } while (elapsedSeconds < nSeconds); break; } if (!performRenderPasses(variance, passesThisIteration, scene, queue, job, sceneResID, sensorResID, samplerResID, integratorResID)) { result = false; break; } const Float secondsIter = computeElapsedSeconds(startIter); const Float lastVarAtEnd = currentVarAtEnd; currentVarAtEnd = secondsIter * variance / remainingTime; Log(EInfo, "Extrapolated var:\n" " Last: %f\n" " Current: %f\n", lastVarAtEnd, currentVarAtEnd); remainingTime -= secondsIter; elapsedSeconds = computeElapsedSeconds(m_startTime); buildSDTree(); if (m_dumpSDTree) { dumpSDTree(scene, sensor); } ++m_iter; m_passesRenderedThisIter = 0; } return result; } bool render(Scene *scene, RenderQueue *queue, const RenderJob *job, int sceneResID, int sensorResID, int samplerResID) { m_sdTree = std::unique_ptr<STree>(new STree(scene->getAABB())); m_iter = 0; m_isFinalIter = false; ref<Scheduler> sched = Scheduler::getInstance(); size_t nCores = sched->getCoreCount(); ref<Sensor> sensor = static_cast<Sensor *>(sched->getResource(sensorResID)); ref<Film> film = sensor->getFilm(); auto properties = Properties("hdrfilm"); properties.setInteger("width", film->getSize().x); properties.setInteger("height", film->getSize().y); m_varianceBuffer = static_cast<Film*>(PluginManager::getInstance()->createObject(MTS_CLASS(Film), properties)); m_varianceBuffer->setDestinationFile(scene->getDestinationFile(), 0); m_squaredImage = new ImageBlock(Bitmap::ESpectrumAlphaWeight, film->getCropSize()); m_image = new ImageBlock(Bitmap::ESpectrumAlphaWeight, film->getCropSize()); m_images.clear(); m_variances.clear(); Log(EInfo, "Starting render job (%ix%i, " SIZE_T_FMT " %s, " SSE_STR ") ..", film->getCropSize().x, film->getCropSize().y, nCores, nCores == 1 ? "core" : "cores"); Thread::initializeOpenMP(nCores); int integratorResID = sched->registerResource(this); bool result = true; m_startTime = std::chrono::steady_clock::now(); m_passesRendered = 0; switch (m_budgetType) { case ESpp: result = renderSPP(scene, queue, job, sceneResID, sensorResID, samplerResID, integratorResID); break; case ESeconds: result = renderTime(scene, queue, job, sceneResID, sensorResID, samplerResID, integratorResID); break; default: Assert(false); break; } sched->unregisterResource(integratorResID); m_progress = nullptr; if (m_sampleCombination == ESampleCombination::EInverseVariance) { // Combine the last 4 images according to their inverse variance film->clear(); ref<ImageBlock> tmp = new ImageBlock(Bitmap::ESpectrum, film->getCropSize()); size_t begin = m_images.size() - std::min(m_images.size(), (size_t)4); Float totalWeight = 0; for (size_t i = begin; i < m_variances.size(); ++i) { totalWeight += 1.0f / m_variances[i]; } for (size_t i = begin; i < m_images.size(); ++i) { m_images[i]->convert(tmp->getBitmap(), 1.0f / m_variances[i] / totalWeight); film->addBitmap(tmp->getBitmap()); } } return result; } void renderBlock(const Scene *scene, const Sensor *sensor, Sampler *sampler, ImageBlock *block, const bool &stop, const std::vector< TPoint2<uint8_t> > &points) const { bool needsApertureSample = sensor->needsApertureSample(); bool needsTimeSample = sensor->needsTimeSample(); RadianceQueryRecord rRec(scene, sampler); Point2 apertureSample(0.5f); Float timeSample = 0.5f; RayDifferential sensorRay; block->clear(); ref<ImageBlock> squaredBlock = new ImageBlock(block->getPixelFormat(), block->getSize(), block->getReconstructionFilter()); squaredBlock->setOffset(block->getOffset()); squaredBlock->clear(); uint32_t queryType = RadianceQueryRecord::ESensorRay; if (!sensor->getFilm()->hasAlpha()) // Don't compute an alpha channel if we don't have to queryType &= ~RadianceQueryRecord::EOpacity; for (size_t i = 0; i < points.size(); ++i) { Point2i offset = Point2i(points[i]) + Vector2i(block->getOffset()); if (stop) break; // @addition // note that the pixel estimate is only needed for our full distribution Spectrum pixelEstimate; if (m_pixelEstimate.get()) { pixelEstimate = m_pixelEstimate->getPixel(offset); } else { // if this is the first iteration, we assume that the image is uniformly 50% gray pixelEstimate = Spectrum { 0.5f }; } for (int j = 0; j < m_sppPerPass; j++) { rRec.newQuery(queryType, sensor->getMedium()); Point2 samplePos(Point2(offset) + Vector2(rRec.nextSample2D())); if (needsApertureSample) apertureSample = rRec.nextSample2D(); if (needsTimeSample) timeSample = rRec.nextSample1D(); Spectrum spec = sensor->sampleRay( sensorRay, samplePos, apertureSample, timeSample); spec = Li(sensorRay, rRec, spec, pixelEstimate); //if (m_isFinalIter) spec = pixelEstimate; block->put(samplePos, spec, rRec.alpha); squaredBlock->put(samplePos, spec * spec, rRec.alpha); sampler->advance(); } } m_squaredImage->put(squaredBlock); m_image->put(block); } void cancel() { const auto& scheduler = Scheduler::getInstance(); for (size_t i = 0; i < m_renderProcesses.size(); ++i) { scheduler->cancel(m_renderProcesses[i]); } } Spectrum sampleMat(const BSDF* bsdf, BSDFSamplingRecord& bRec, Float& woPdf, Float& bsdfPdf, Float& dTreePdf, Float bsdfSamplingFraction, RadianceQueryRecord& rRec, const DTreeWrapper* dTree) const { Point2 sample = rRec.nextSample2D(); auto type = bsdf->getType(); if (!m_isBuilt || !dTree || (type & BSDF::EDelta) == (type & BSDF::EAll)) { auto result = bsdf->sample(bRec, bsdfPdf, sample); woPdf = bsdfPdf; dTreePdf = 0; return result; } Spectrum result; if (sample.x < bsdfSamplingFraction) { sample.x /= bsdfSamplingFraction; result = bsdf->sample(bRec, bsdfPdf, sample); if (result.isZero()) { woPdf = bsdfPdf = dTreePdf = 0; return Spectrum{0.0f}; } // If we sampled a delta component, then we have a 0 probability // of sampling that direction via guiding, thus we can return early. if (bRec.sampledType & BSDF::EDelta) { dTreePdf = 0; woPdf = bsdfPdf * bsdfSamplingFraction; return result / bsdfSamplingFraction; } result *= bsdfPdf; } else { sample.x = (sample.x - bsdfSamplingFraction) / (1 - bsdfSamplingFraction); bRec.wo = bRec.its.toLocal(dTree->sample(rRec.sampler)); result = bsdf->eval(bRec); } pdfMat(woPdf, bsdfPdf, dTreePdf, bsdfSamplingFraction, bsdf, bRec, dTree); if (woPdf == 0) { return Spectrum{0.0f}; } return result / woPdf; } void pdfMat(Float& woPdf, Float& bsdfPdf, Float& dTreePdf, Float bsdfSamplingFraction, const BSDF* bsdf, const BSDFSamplingRecord& bRec, const DTreeWrapper* dTree) const { dTreePdf = 0; auto type = bsdf->getType(); if (!m_isBuilt || !dTree || (type & BSDF::EDelta) == (type & BSDF::EAll)) { woPdf = bsdfPdf = bsdf->pdf(bRec); return; } bsdfPdf = bsdf->pdf(bRec); if (!std::isfinite(bsdfPdf)) { woPdf = 0; return; } dTreePdf = dTree->pdf(bRec.its.toWorld(bRec.wo)); woPdf = bsdfSamplingFraction * bsdfPdf + (1 - bsdfSamplingFraction) * dTreePdf; } Spectrum Li(const RayDifferential &r, RadianceQueryRecord &rRec) const { NotImplementedError("Pixel estimate and throughput must be provided for full distribution"); } Spectrum Li( const RayDifferential &r, RadianceQueryRecord &rRec, Spectrum throughput, const Spectrum &pixelEstimate ) const { struct Vertex { DTreeWrapper* dTree; Vector dTreeVoxelSize; Ray ray; Spectrum throughput; Spectrum bsdfVal; Spectrum radiance; Float woPdf, bsdfPdf, dTreePdf; Float woMisWeight; bool isDelta; void record(const Spectrum& r) { radiance += r; } void commit(STree& sdTree, Float statisticalWeight, ESpatialFilter spatialFilter, EDirectionalFilter directionalFilter, EBsdfSamplingFractionLoss bsdfSamplingFractionLoss, EDistribution distribution, Sampler* sampler, const Spectrum &pixelEstimate) { if (!(woPdf > 0) || !radiance.isValid() || !bsdfVal.isValid()) { return; } Spectrum localRadiance = Spectrum{0.0f}; if (throughput[0] * woPdf > Epsilon) localRadiance[0] = radiance[0] / throughput[0]; if (throughput[1] * woPdf > Epsilon) localRadiance[1] = radiance[1] / throughput[1]; if (throughput[2] * woPdf > Epsilon) localRadiance[2] = radiance[2] / throughput[2]; // @addition // target densities Float value = 0; switch (distribution) { case EDistribution::ERadiance: value = localRadiance.average(); break; case EDistribution::ESimple: value = (bsdfVal * localRadiance).average(); // partial integrand if (woMisWeight > 0) // mis compensation value *= woMisWeight; value = std::pow(value, 2); // second moment break; case EDistribution::EFull: // note that since 'radiance = throughput * localRadiance', // we do not need a multiplication by throughput here. value = (radiance / pixelEstimate * woPdf).average(); // full integrand if (woMisWeight > 0) // mis compensation value *= woMisWeight; value = std::pow(value, 2); // second moment break; default: Assert(false); } // @addition // selection probability Float lossValue = 0; switch (distribution) { case EDistribution::ERadiance: // previous selection probability loss (Müller et al.) lossValue = (localRadiance * bsdfVal).average(); break; case EDistribution::ESimple: case EDistribution::EFull: // our selection probability loss // note that since 'radiance = throughput * localRadiance', // we do not need a multiplication by throughput here. lossValue = (radiance / pixelEstimate * woPdf).average(); // full integrand break; default: Assert(false); } DTreeRecord rec{ ray.d, value, lossValue, woPdf, bsdfPdf, dTreePdf, statisticalWeight, isDelta }; switch (spatialFilter) { case ESpatialFilter::ENearest: dTree->record(rec, directionalFilter, bsdfSamplingFractionLoss); break; case ESpatialFilter::EStochasticBox: { DTreeWrapper* splatDTree = dTree; // Jitter the actual position within the // filter box to perform stochastic filtering. Vector offset = dTreeVoxelSize; offset.x *= sampler->next1D() - 0.5f; offset.y *= sampler->next1D() - 0.5f; offset.z *= sampler->next1D() - 0.5f; Point origin = sdTree.aabb().clip(ray.o + offset); splatDTree = sdTree.dTreeWrapper(origin); if (splatDTree) { splatDTree->record(rec, directionalFilter, bsdfSamplingFractionLoss); } break; } case ESpatialFilter::EBox: sdTree.record(ray.o, dTreeVoxelSize, rec, directionalFilter, bsdfSamplingFractionLoss); break; } } }; static const int MAX_NUM_VERTICES = 32; std::array<Vertex, MAX_NUM_VERTICES> vertices; /* Some aliases and local variables */ const Scene *scene = rRec.scene; Intersection &its = rRec.its; MediumSamplingRecord mRec; RayDifferential ray(r); Spectrum Li(0.0f); Float eta = 1.0f; /* Perform the first ray intersection (or ignore if the intersection has already been provided). */ rRec.rayIntersect(ray); bool scattered = false; int nVertices = 0; auto recordRadiance = [&](Spectrum radiance) { Li += radiance; for (int i = 0; i < nVertices; ++i) { vertices[i].record(radiance); } }; while (rRec.depth <= m_maxDepth || m_maxDepth < 0) { /* ==================================================================== */ /* Radiative Transfer Equation sampling */ /* ==================================================================== */ if (rRec.medium && rRec.medium->sampleDistance(Ray(ray, 0, its.t), mRec, rRec.sampler)) { /* Sample the integral \int_x^y tau(x, x') [ \sigma_s \int_{S^2} \rho(\omega,\omega') L(x,\omega') d\omega' ] dx' */ const PhaseFunction *phase = mRec.getPhaseFunction(); if (rRec.depth >= m_maxDepth && m_maxDepth != -1) // No more scattering events allowed break; throughput *= mRec.sigmaS * mRec.transmittance / mRec.pdfSuccess; /* ==================================================================== */ /* Luminaire sampling */ /* ==================================================================== */ /* Estimate the single scattering component if this is requested */ DirectSamplingRecord dRec(mRec.p, mRec.time); if (rRec.type & RadianceQueryRecord::EDirectMediumRadiance) { int interactions = m_maxDepth - rRec.depth - 1; Spectrum value = scene->sampleAttenuatedEmitterDirect( dRec, rRec.medium, interactions, rRec.nextSample2D(), rRec.sampler); if (!value.isZero()) { const Emitter *emitter = static_cast<const Emitter *>(dRec.object); /* Evaluate the phase function */ PhaseFunctionSamplingRecord pRec(mRec, -ray.d, dRec.d); Float phaseVal = phase->eval(pRec); if (phaseVal != 0) { /* Calculate prob. of having sampled that direction using phase function sampling */ Float phasePdf = (emitter->isOnSurface() && dRec.measure == ESolidAngle) ? phase->pdf(pRec) : (Float) 0.0f; /* Weight using the power heuristic */ const Float weight = miWeight(dRec.pdf, phasePdf); recordRadiance(throughput * value * phaseVal * weight); } } } /* ==================================================================== */ /* Phase function sampling */ /* ==================================================================== */ Float phasePdf; PhaseFunctionSamplingRecord pRec(mRec, -ray.d); Float phaseVal = phase->sample(pRec, phasePdf, rRec.sampler); if (phaseVal == 0) break; throughput *= phaseVal; /* Trace a ray in this direction */ ray = Ray(mRec.p, pRec.wo, ray.time); ray.mint = 0; Spectrum value(0.0f); rayIntersectAndLookForEmitter(scene, rRec.sampler, rRec.medium, m_maxDepth - rRec.depth - 1, ray, its, dRec, value); /* If a luminaire was hit, estimate the local illumination and weight using the power heuristic */ if (!value.isZero() && (rRec.type & RadianceQueryRecord::EDirectMediumRadiance)) { const Float emitterPdf = scene->pdfEmitterDirect(dRec); recordRadiance(throughput * value * miWeight(phasePdf, emitterPdf)); } /* ==================================================================== */ /* Multiple scattering */ /* ==================================================================== */ /* Stop if multiple scattering was not requested */ if (!(rRec.type & RadianceQueryRecord::EIndirectMediumRadiance)) break; rRec.type = RadianceQueryRecord::ERadianceNoEmission; if (rRec.depth++ >= m_rrDepth) { /* Russian roulette: try to keep path weights equal to one, while accounting for the solid angle compression at refractive index boundaries. Stop with at least some probability to avoid getting stuck (e.g. due to total internal reflection) */ Float q = std::min(throughput.max() * eta * eta, (Float) 0.95f); if (rRec.nextSample1D() >= q) break; throughput /= q; } } else { /* Sample tau(x, y) (Surface integral). This happens with probability mRec.pdfFailure Account for this and multiply by the proper per-color-channel transmittance. */ if (rRec.medium) throughput *= mRec.transmittance / mRec.pdfFailure; if (!its.isValid()) { /* If no intersection could be found, possibly return attenuated radiance from a background luminaire */ if ((rRec.type & RadianceQueryRecord::EEmittedRadiance) && (!m_hideEmitters || scattered)) { Spectrum value = throughput * scene->evalEnvironment(ray); if (rRec.medium) value *= rRec.medium->evalTransmittance(ray, rRec.sampler); recordRadiance(value); } break; } /* Possibly include emitted radiance if requested */ if (its.isEmitter() && (rRec.type & RadianceQueryRecord::EEmittedRadiance) && (!m_hideEmitters || scattered)) recordRadiance(throughput * its.Le(-ray.d)); /* Include radiance from a subsurface integrator if requested */ if (its.hasSubsurface() && (rRec.type & RadianceQueryRecord::ESubsurfaceRadiance)) recordRadiance(throughput * its.LoSub(scene, rRec.sampler, -ray.d, rRec.depth)); if (rRec.depth >= m_maxDepth && m_maxDepth != -1) break; /* Prevent light leaks due to the use of shading normals */ Float wiDotGeoN = -dot(its.geoFrame.n, ray.d), wiDotShN = Frame::cosTheta(its.wi); if (wiDotGeoN * wiDotShN < 0 && m_strictNormals) break; const BSDF *bsdf = its.getBSDF(); Vector dTreeVoxelSize; DTreeWrapper* dTree = nullptr; // We only guide smooth BRDFs for now. Analytic product sampling // would be conceivable for discrete decisions such as refraction vs // reflection. if (bsdf->getType() & BSDF::ESmooth) { dTree = m_sdTree->dTreeWrapper(its.p, dTreeVoxelSize); } Float bsdfSamplingFraction = m_bsdfSamplingFraction; if (dTree && m_bsdfSamplingFractionLoss != EBsdfSamplingFractionLoss::ENone) { bsdfSamplingFraction = dTree->bsdfSamplingFraction(); } /* ==================================================================== */ /* BSDF sampling */ /* ==================================================================== */ /* Sample BSDF * cos(theta) */ BSDFSamplingRecord bRec(its, rRec.sampler, ERadiance); Float woPdf, bsdfPdf, dTreePdf; Spectrum bsdfWeight = sampleMat(bsdf, bRec, woPdf, bsdfPdf, dTreePdf, bsdfSamplingFraction, rRec, dTree); /* ==================================================================== */ /* Luminaire sampling */ /* ==================================================================== */ DirectSamplingRecord dRec(its); /* Estimate the direct illumination if this is requested */ if (m_doNee && (rRec.type & RadianceQueryRecord::EDirectSurfaceRadiance) && (bsdf->getType() & BSDF::ESmooth)) { int interactions = m_maxDepth - rRec.depth - 1; Spectrum value = scene->sampleAttenuatedEmitterDirect( dRec, its, rRec.medium, interactions, rRec.nextSample2D(), rRec.sampler); if (!value.isZero()) { BSDFSamplingRecord bRec(its, its.toLocal(dRec.d)); Float woDotGeoN = dot(its.geoFrame.n, dRec.d); /* Prevent light leaks due to the use of shading normals */ if (!m_strictNormals || woDotGeoN * Frame::cosTheta(bRec.wo) > 0) { /* Evaluate BSDF * cos(theta) */ const Spectrum bsdfVal = bsdf->eval(bRec); /* Calculate prob. of having generated that direction using BSDF sampling */ const Emitter *emitter = static_cast<const Emitter *>(dRec.object); Float woPdf = 0, bsdfPdf = 0, dTreePdf = 0; if (emitter->isOnSurface() && dRec.measure == ESolidAngle) { pdfMat(woPdf, bsdfPdf, dTreePdf, bsdfSamplingFraction, bsdf, bRec, dTree); } /* Weight using the power heuristic */ const Float weight = miWeight(dRec.pdf, woPdf); value *= bsdfVal; Spectrum L = throughput * value * weight; if (!m_isFinalIter && m_diStrategy != EDIStrategy::ENoDI) { if (dTree) { Vertex v = Vertex{ dTree, dTreeVoxelSize, Ray(its.p, dRec.d, 0), throughput * bsdfVal / dRec.pdf, bsdfVal, m_diStrategy == EDIStrategy::EUnweightedDI ? L : L * miWeight(woPdf, dRec.pdf), dRec.pdf, bsdfPdf, dTreePdf, dTreePdf / woPdf, false, }; v.commit(*m_sdTree, 1.0f, m_spatialFilter, m_directionalFilter, m_isBuilt ? m_bsdfSamplingFractionLoss : EBsdfSamplingFractionLoss::ENone, m_distribution, rRec.sampler, pixelEstimate); } } recordRadiance(L); } } } // BSDF handling if (bsdfWeight.isZero()) break; /* Prevent light leaks due to the use of shading normals */ const Vector wo = its.toWorld(bRec.wo); Float woDotGeoN = dot(its.geoFrame.n, wo); if (woDotGeoN * Frame::cosTheta(bRec.wo) <= 0 && m_strictNormals) break; /* Trace a ray in this direction */ ray = Ray(its.p, wo, ray.time); /* Keep track of the throughput, medium, and relative refractive index along the path */ throughput *= bsdfWeight; eta *= bRec.eta; if (its.isMediumTransition()) rRec.medium = its.getTargetMedium(ray.d); /* Handle index-matched medium transitions specially */ if (bRec.sampledType == BSDF::ENull) { if (!(rRec.type & RadianceQueryRecord::EIndirectSurfaceRadiance)) break; // There exist materials that are smooth/null hybrids (e.g. the mask BSDF), which means that // for optimal-sampling-fraction optimization we need to record null transitions for such BSDFs. if (m_bsdfSamplingFractionLoss != EBsdfSamplingFractionLoss::ENone && dTree && nVertices < MAX_NUM_VERTICES && !m_isFinalIter) { if (1 / woPdf > 0) { vertices[nVertices] = Vertex{ dTree, dTreeVoxelSize, ray, throughput, bsdfWeight * woPdf, Spectrum{0.0f}, woPdf, bsdfPdf, dTreePdf, dTreePdf / woPdf, true, }; ++nVertices; } } rRec.type = scattered ? RadianceQueryRecord::ERadianceNoEmission : RadianceQueryRecord::ERadiance; scene->rayIntersect(ray, its); rRec.depth++; continue; } Spectrum value(0.0f); rayIntersectAndLookForEmitter(scene, rRec.sampler, rRec.medium, m_maxDepth - rRec.depth - 1, ray, its, dRec, value); /* If a luminaire was hit, estimate the local illumination and weight using the power heuristic */ if (rRec.type & RadianceQueryRecord::EDirectSurfaceRadiance) { bool isDelta = bRec.sampledType & BSDF::EDelta; const Float emitterPdf = (m_doNee && !isDelta && !value.isZero()) ? scene->pdfEmitterDirect(dRec) : 0; const Float weight = miWeight(woPdf, emitterPdf); Spectrum L = throughput * value * weight; if (!L.isZero()) { recordRadiance(L); } if ((!isDelta || m_bsdfSamplingFractionLoss != EBsdfSamplingFractionLoss::ENone) && dTree && nVertices < MAX_NUM_VERTICES && !m_isFinalIter) { if (1 / woPdf > 0) { Spectrum Ldi { 0.f }; if (m_doNee) { switch (m_diStrategy) { case EDIStrategy::ENoDI: Ldi = Spectrum { 0.f }; break; case EDIStrategy::EWeightedDI: Ldi = L * miWeight(woPdf, emitterPdf); break; case EDIStrategy::EUnweightedDI: Ldi = L; break; default: Assert(false); } } else { Ldi = L; } vertices[nVertices] = Vertex{ dTree, dTreeVoxelSize, ray, throughput, bsdfWeight * woPdf, Ldi, woPdf, bsdfPdf, dTreePdf, dTreePdf / woPdf, isDelta, }; ++nVertices; } } } /* ==================================================================== */ /* Indirect illumination */ /* ==================================================================== */ /* Stop if indirect illumination was not requested */ if (!(rRec.type & RadianceQueryRecord::EIndirectSurfaceRadiance)) break; rRec.type = RadianceQueryRecord::ERadianceNoEmission; // Russian roulette if (rRec.depth++ >= m_rrDepth) { Float successProb = 1.0f; if (dTree && !(bRec.sampledType & BSDF::EDelta)) { if (!m_isBuilt) { successProb = throughput.max() * eta * eta; } else { // The adjoint russian roulette implementation of Mueller et al. [2017] // was broken, effectively turning off russian roulette entirely. // For reproducibility's sake, we therefore removed adjoint russian roulette // from this codebase rather than fixing it. } successProb = std::max(0.1f, std::min(successProb, 0.99f)); } if (rRec.nextSample1D() >= successProb) break; throughput /= successProb; } } scattered = true; } avgPathLength.incrementBase(); avgPathLength += rRec.depth; if (nVertices > 0 && !m_isFinalIter) { for (int i = 0; i < nVertices; ++i) { vertices[i].commit(*m_sdTree, 1.0f, m_spatialFilter, m_directionalFilter, m_isBuilt ? m_bsdfSamplingFractionLoss : EBsdfSamplingFractionLoss::ENone, m_distribution, rRec.sampler, pixelEstimate); } } return Li; } /** * This function is called by the recursive ray tracing above after * having sampled a direction from a BSDF/phase function. Due to the * way in which this integrator deals with index-matched boundaries, * it is necessarily a bit complicated (though the improved performance * easily pays for the extra effort). * * This function * * 1. Intersects 'ray' against the scene geometry and returns the * *first* intersection via the '_its' argument. * * 2. It checks whether the intersected shape was an emitter, or if * the ray intersects nothing and there is an environment emitter. * In this case, it returns the attenuated emittance, as well as * a DirectSamplingRecord that can be used to query the hypothetical * sampling density at the emitter. * * 3. If current shape is an index-matched medium transition, the * integrator keeps on looking on whether a light source eventually * follows after a potential chain of index-matched medium transitions, * while respecting the specified 'maxDepth' limits. It then returns * the attenuated emittance of this light source, while accounting for * all attenuation that occurs on the wya. */ void rayIntersectAndLookForEmitter(const Scene *scene, Sampler *sampler, const Medium *medium, int maxInteractions, Ray ray, Intersection &_its, DirectSamplingRecord &dRec, Spectrum &value) const { Intersection its2, *its = &_its; Spectrum transmittance(1.0f); bool surface = false; int interactions = 0; while (true) { surface = scene->rayIntersect(ray, *its); if (medium) transmittance *= medium->evalTransmittance(Ray(ray, 0, its->t), sampler); if (surface && (interactions == maxInteractions || !(its->getBSDF()->getType() & BSDF::ENull) || its->isEmitter())) { /* Encountered an occluder / light source */ break; } if (!surface) break; if (transmittance.isZero()) return; if (its->isMediumTransition()) medium = its->getTargetMedium(ray.d); Vector wo = its->shFrame.toLocal(ray.d); BSDFSamplingRecord bRec(*its, -wo, wo, ERadiance); bRec.typeMask = BSDF::ENull; transmittance *= its->getBSDF()->eval(bRec, EDiscrete); ray.o = ray(its->t); ray.mint = Epsilon; its = &its2; if (++interactions > 100) { /// Just a precaution.. Log(EWarn, "rayIntersectAndLookForEmitter(): round-off error issues?"); return; } } if (surface) { /* Intersected something - check if it was a luminaire */ if (its->isEmitter()) { dRec.setQuery(ray, *its); value = transmittance * its->Le(-ray.d); } } else { /* Intersected nothing -- perhaps there is an environment map? */ const Emitter *env = scene->getEnvironmentEmitter(); if (env && env->fillDirectSamplingRecord(dRec, ray)) { value = transmittance * env->evalEnvironment(RayDifferential(ray)); dRec.dist = std::numeric_limits<Float>::infinity(); its->t = std::numeric_limits<Float>::infinity(); } } } Float miWeight(Float pdfA, Float pdfB) const { pdfA *= pdfA; pdfB *= pdfB; return pdfA / (pdfA + pdfB); } std::string toString() const { std::ostringstream oss; oss << "GuidedPathTracer[" << endl << " maxDepth = " << m_maxDepth << "," << endl << " rrDepth = " << m_rrDepth << "," << endl << " strictNormals = " << m_strictNormals << endl << "]"; return oss.str(); } private: /// The datastructure for guiding paths. std::unique_ptr<STree> m_sdTree; /// The squared values of our currently rendered image. Used to estimate variance. mutable ref<ImageBlock> m_squaredImage; /// The currently rendered image. Used to estimate variance. mutable ref<ImageBlock> m_image; std::vector<ref<Bitmap>> m_images; ref<Bitmap> m_pixelEstimate; std::vector<Float> m_variances; /// This contains the currently estimated variance. mutable ref<Film> m_varianceBuffer; /// The modes of NEE which are supported. enum ENee { ENever, EKickstart, EAlways, }; /** How to perform next event estimation (NEE). The following values are valid: - "never": Never performs NEE. - "kickstart": Performs NEE for the first few iterations to initialize the SDTree with good direct illumination estimates. - "always": Always performs NEE. Default = "never" */ std::string m_neeStr; ENee m_nee; /// Whether Li should currently perform NEE (automatically set during rendering based on m_nee). bool m_doNee; enum EBudget { ESpp, ESeconds, }; /** What type of budget to use. The following values are valid: - "spp": Budget is the number of samples per pixel. - "seconds": Budget is a time in seconds. Default = "seconds" */ std::string m_budgetStr; EBudget m_budgetType; Float m_budget; int m_trainingIterations; bool m_isBuilt = false; int m_iter; bool m_isFinalIter = false; int m_sppPerPass; int m_passesRendered; int m_passesRenderedThisIter; mutable std::unique_ptr<ProgressReporter> m_progress; std::vector<ref<BlockedRenderProcess>> m_renderProcesses; /** How to combine the samples from all path-guiding iterations: - "discard": Discard all but the last iteration. - "automatic": Discard all but the last iteration, but automatically assign an appropriately larger budget to the last [Mueller et al. 2018]. - "inversevar": Combine samples of the last 4 iterations based on their mean pixel variance [Mueller et al. 2018]. Default = "automatic" (for reproducibility) Recommended = "inversevar" */ std::string m_sampleCombinationStr; ESampleCombination m_sampleCombination; /// Maximum memory footprint of the SDTree in MB. Stops subdividing once reached. -1 to disable. int m_sdTreeMaxMemory; /** The spatial filter to use when splatting radiance samples into the SDTree. The following values are valid: - "nearest": No filtering [Mueller et al. 2017]. - "stochastic": Stochastic box filter; improves upon Mueller et al. [2017] at nearly no computational cost. - "box": Box filter; improves the quality further at significant additional computational cost. Default = "nearest" (for reproducibility) Recommended = "stochastic" */ std::string m_spatialFilterStr; ESpatialFilter m_spatialFilter; /** The directional filter to use when splatting radiance samples into the SDTree. The following values are valid: - "nearest": No filtering [Mueller et al. 2017]. - "box": Box filter; improves upon Mueller et al. [2017] at nearly no computational cost. Default = "nearest" (for reproducibility) Recommended = "box" */ std::string m_directionalFilterStr; EDirectionalFilter m_directionalFilter; /** The guiding distribution that should be approximated. The following values are valid: - "radiance": Previous guiding distribution [Mueller et al. 2017]. - "simple": Approximates parts of the integrand Robust for short renders, but worse than "full" for long renders - "full": Approximates the full integrand Recommended for very long renders, otherwise use "simple" Default = "radiance" (for reproducibility) Recommended = "simple" for short renders */ std::string m_distributionStr; EDistribution m_distribution; EDIStrategy m_diStrategy; /** Leaf nodes of the spatial binary tree are subdivided if the number of samples they received in the last iteration exceeds c * sqrt(2^k) where c is this value and k is the iteration index. The first iteration has k==0. Default = 12000 (for reproducibility) Recommended = 4000 */ int m_sTreeThreshold; /** Leaf nodes of the directional quadtree are subdivided if the fraction of energy they carry exceeds this value. Default = 0.01 (1%) */ Float m_dTreeThreshold; /** When guiding, we perform MIS with the balance heuristic between the guiding distribution and the BSDF, combined with probabilistically choosing one of the two sampling methods. This factor controls how often the BSDF is sampled vs. how often the guiding distribution is sampled. Default = 0.5 (50%) */ Float m_bsdfSamplingFraction; /** The loss function to use when learning the bsdfSamplingFraction using gradient descent, following the theory of Neural Importance Sampling [Mueller et al. 2018]. The following values are valid: - "none": No learning (uses the fixed `m_bsdfSamplingFraction`). - "kl": Optimizes bsdfSamplingFraction w.r.t. the KL divergence. - "var": Optimizes bsdfSamplingFraction w.r.t. variance. Default = "none" (for reproducibility) Recommended = "kl" */ std::string m_bsdfSamplingFractionLossStr; EBsdfSamplingFractionLoss m_bsdfSamplingFractionLoss; /** Whether to dump a binary representation of the SD-Tree to disk after every iteration. The dumped SD-Tree can be visualized with the accompanying visualizer tool. Default = false */ bool m_dumpSDTree; /// The time at which rendering started. std::chrono::steady_clock::time_point m_startTime; std::string m_configLog; public: MTS_DECLARE_CLASS() }; MTS_IMPLEMENT_CLASS(GuidedPathTracer, false, MonteCarloIntegrator) MTS_EXPORT_PLUGIN(GuidedPathTracer, "Guided path tracer"); MTS_NAMESPACE_END
104,198
C++
.cpp
2,322
32.270457
262
0.542161
iRath96/variance-aware-path-guiding
35
7
0
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
1,541,756
dataref_helpers.cpp
FarukEroglu2048_Enhanced-Cloudscapes/src/dataref_helpers.cpp
#include <dataref_helpers.hpp> int read_int_callback(void* float_pointer) { return *static_cast<int*>(float_pointer); } void write_int_callback(void* float_pointer, int new_value) { *static_cast<int*>(float_pointer) = new_value; } float read_float_callback(void* float_pointer) { return *static_cast<float*>(float_pointer); } void write_float_callback(void* float_pointer, float new_value) { *static_cast<float*>(float_pointer) = new_value; } int read_vec3_callback(void* vec3_pointer, float* output_values, int read_offset, int read_size) { glm::vec3& input_vec3 = *static_cast<glm::vec3*>(vec3_pointer); if (output_values != nullptr) { int read_start = read_offset % input_vec3.length(); int read_end = read_start + read_size; if (read_end < read_start) read_end = read_start; else if (read_end > input_vec3.length()) read_end = input_vec3.length(); for (int index = read_start; index < read_end; index++) output_values[index] = input_vec3[index]; return read_end - read_start; } else return input_vec3.length(); } void write_vec3_callback(void* vector_pointer, float* input_values, int write_offset, int write_size) { glm::vec3& output_vec3 = *static_cast<glm::vec3*>(vector_pointer); int write_start = write_offset % output_vec3.length(); int write_end = write_start + write_size; if (write_end < write_start) write_end = write_start; else if (write_end > output_vec3.length()) write_end = output_vec3.length(); for (int index = write_start; index < write_end; index++) output_vec3[index] = input_values[index]; } XPLMDataRef export_int_dataref(char* dataref_name, int initial_value) { int* int_pointer = new int(initial_value); return XPLMRegisterDataAccessor(dataref_name, xplmType_Int, 1, read_int_callback, write_int_callback, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, int_pointer, int_pointer); } XPLMDataRef export_float_dataref(char* dataref_name, float initial_value) { float* float_pointer = new float(initial_value); return XPLMRegisterDataAccessor(dataref_name, xplmType_Float, 1, nullptr, nullptr, read_float_callback, write_float_callback, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, float_pointer, float_pointer); } XPLMDataRef export_vec3_dataref(char* dataref_name, glm::vec3 initial_value) { glm::vec3* vec3_pointer = new glm::vec3(initial_value); return XPLMRegisterDataAccessor(dataref_name, xplmType_FloatArray, 1, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, read_vec3_callback, write_vec3_callback, nullptr, nullptr, vec3_pointer, vec3_pointer); }
2,628
C++
.cpp
55
45.854545
230
0.751076
FarukEroglu2048/Enhanced-Cloudscapes
34
12
2
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,757
rendering_program.cpp
FarukEroglu2048_Enhanced-Cloudscapes/src/rendering_program.cpp
#include <rendering_program.hpp> #include <opengl_helpers.hpp> #include <simulator_objects.hpp> #include <plugin_objects.hpp> #include <XPLMGraphics.h> #include <glm/gtc/type_ptr.hpp> namespace rendering_program { GLint reference; GLint near_clip_z; GLint far_clip_z; GLint previous_mvp_matrix; GLint current_mvp_matrix; GLint inverse_modelview_matrix; GLint inverse_projection_matrix; GLint skip_fragments; GLint frame_index; GLint sample_step_count; GLint sun_step_count; GLint maximum_sample_step_size; GLint maximum_sun_step_size; GLint use_blue_noise_dithering; GLint cloud_map_scale; GLint base_noise_scale; GLint detail_noise_scale; GLint blue_noise_scale; GLint cloud_types; GLint cloud_bases; GLint cloud_tops; GLint cloud_coverages; GLint cloud_densities; GLint base_noise_ratios; GLint detail_noise_ratios; GLint wind_offsets; GLint base_anvil; GLint top_anvil; GLint fade_start_distance; GLint fade_end_distance; GLint light_attenuation; GLint sun_direction; GLint sun_tint; GLint sun_gain; GLint ambient_tint; GLint ambient_gain; GLint mie_scattering; GLint atmosphere_bottom_tint; GLint atmosphere_top_tint; GLint atmospheric_blending; void initialize() { GLuint vertex_shader = load_shader("Resources/plugins/Enhanced Cloudscapes/shaders/rendering/vertex_shader.glsl", GL_VERTEX_SHADER); GLuint fragment_shader = load_shader("Resources/plugins/Enhanced Cloudscapes/shaders/rendering/fragment_shader.glsl", GL_FRAGMENT_SHADER); reference = create_program(vertex_shader, fragment_shader); glUseProgram(reference); GLint previous_depth_texture = glGetUniformLocation(reference, "previous_depth_texture"); GLint current_depth_texture = glGetUniformLocation(reference, "current_depth_texture"); GLint cloud_map_textures = glGetUniformLocation(reference, "cloud_map_textures"); GLint base_noise_texture = glGetUniformLocation(reference, "base_noise_texture"); GLint detail_noise_texture = glGetUniformLocation(reference, "detail_noise_texture"); GLint blue_noise_texture = glGetUniformLocation(reference, "blue_noise_texture"); GLint previous_rendering_texture = glGetUniformLocation(reference, "previous_rendering_texture"); glUniform1i(previous_depth_texture, 0); glUniform1i(current_depth_texture, 1); GLint texture_indices[CLOUD_LAYER_COUNT] = {2, 3, 4}; glUniform1iv(cloud_map_textures, CLOUD_LAYER_COUNT, texture_indices); glUniform1i(base_noise_texture, 5); glUniform1i(detail_noise_texture, 6); glUniform1i(blue_noise_texture, 7); glUniform1i(previous_rendering_texture, 8); near_clip_z = glGetUniformLocation(reference, "near_clip_z"); far_clip_z = glGetUniformLocation(reference, "far_clip_z"); previous_mvp_matrix = glGetUniformLocation(reference, "previous_mvp_matrix"); current_mvp_matrix = glGetUniformLocation(reference, "current_mvp_matrix"); inverse_modelview_matrix = glGetUniformLocation(reference, "inverse_modelview_matrix"); inverse_projection_matrix = glGetUniformLocation(reference, "inverse_projection_matrix"); skip_fragments = glGetUniformLocation(reference, "skip_fragments"); frame_index = glGetUniformLocation(reference, "frame_index"); sample_step_count = glGetUniformLocation(reference, "sample_step_count"); sun_step_count = glGetUniformLocation(reference, "sun_step_count"); maximum_sample_step_size = glGetUniformLocation(reference, "maximum_sample_step_size"); maximum_sun_step_size = glGetUniformLocation(reference, "maximum_sun_step_size"); use_blue_noise_dithering = glGetUniformLocation(reference, "use_blue_noise_dithering"); cloud_map_scale = glGetUniformLocation(reference, "cloud_map_scale"); base_noise_scale = glGetUniformLocation(reference, "base_noise_scale"); detail_noise_scale = glGetUniformLocation(reference, "detail_noise_scale"); blue_noise_scale = glGetUniformLocation(reference, "blue_noise_scale"); cloud_types = glGetUniformLocation(reference, "cloud_types"); cloud_bases = glGetUniformLocation(reference, "cloud_bases"); cloud_tops = glGetUniformLocation(reference, "cloud_tops"); cloud_coverages = glGetUniformLocation(reference, "cloud_coverages"); cloud_densities = glGetUniformLocation(reference, "cloud_densities"); base_noise_ratios = glGetUniformLocation(reference, "base_noise_ratios"); detail_noise_ratios = glGetUniformLocation(reference, "detail_noise_ratios"); wind_offsets = glGetUniformLocation(reference, "wind_offsets"); base_anvil = glGetUniformLocation(reference, "base_anvil"); top_anvil = glGetUniformLocation(reference, "top_anvil"); fade_start_distance = glGetUniformLocation(reference, "fade_start_distance"); fade_end_distance = glGetUniformLocation(reference, "fade_end_distance"); light_attenuation = glGetUniformLocation(reference, "light_attenuation"); sun_direction = glGetUniformLocation(reference, "sun_direction"); sun_tint = glGetUniformLocation(reference, "sun_tint"); sun_gain = glGetUniformLocation(reference, "sun_gain"); ambient_tint = glGetUniformLocation(reference, "ambient_tint"); ambient_gain = glGetUniformLocation(reference, "ambient_gain"); mie_scattering = glGetUniformLocation(reference, "mie_scattering"); atmosphere_bottom_tint = glGetUniformLocation(reference, "atmosphere_bottom_tint"); atmosphere_top_tint = glGetUniformLocation(reference, "atmosphere_top_tint"); atmospheric_blending = glGetUniformLocation(reference, "atmospheric_blending"); glUseProgram(EMPTY_OBJECT); } void call() { XPLMSetGraphicsState(0, 9, 0, 0, 0, 0, 0); GLint previous_framebuffer; glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &previous_framebuffer); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, plugin_objects::framebuffer); glViewport(0, 0, simulator_objects::current_rendering_resolution.x, simulator_objects::current_rendering_resolution.y); glBindVertexArray(plugin_objects::vertex_array); glUseProgram(reference); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, plugin_objects::previous_depth_texture); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, plugin_objects::current_depth_texture); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, plugin_objects::cloud_map_textures[0]); glActiveTexture(GL_TEXTURE3); glBindTexture(GL_TEXTURE_2D, plugin_objects::cloud_map_textures[1]); glActiveTexture(GL_TEXTURE4); glBindTexture(GL_TEXTURE_2D, plugin_objects::cloud_map_textures[2]); glActiveTexture(GL_TEXTURE5); glBindTexture(GL_TEXTURE_3D, plugin_objects::base_noise_texture); glActiveTexture(GL_TEXTURE6); glBindTexture(GL_TEXTURE_3D, plugin_objects::detail_noise_texture); glActiveTexture(GL_TEXTURE7); glBindTexture(GL_TEXTURE_2D, plugin_objects::blue_noise_texture); glActiveTexture(GL_TEXTURE8); glBindTexture(GL_TEXTURE_2D, plugin_objects::previous_rendering_texture); glUniform1f(near_clip_z, simulator_objects::near_clip_z); glUniform1f(far_clip_z, simulator_objects::far_clip_z); glUniformMatrix4fv(previous_mvp_matrix, 1, GL_FALSE, glm::value_ptr(glm::mat4(simulator_objects::previous_mvp_matrix))); glUniformMatrix4fv(current_mvp_matrix, 1, GL_FALSE, glm::value_ptr(glm::mat4(simulator_objects::current_mvp_matrix))); glUniformMatrix4fv(inverse_modelview_matrix, 1, GL_FALSE, glm::value_ptr(glm::mat4(simulator_objects::inverse_modelview_matrix))); glUniformMatrix4fv(inverse_projection_matrix, 1, GL_FALSE, glm::value_ptr(glm::mat4(simulator_objects::inverse_projection_matrix))); glUniform1i(skip_fragments, simulator_objects::skip_fragments); glUniform1i(frame_index, simulator_objects::frame_index); glUniform1i(sample_step_count, simulator_objects::sample_step_count); glUniform1i(sun_step_count, simulator_objects::sun_step_count); glUniform1f(maximum_sample_step_size, simulator_objects::maximum_sample_step_size); glUniform1f(maximum_sun_step_size, simulator_objects::maximum_sun_step_size); glUniform1i(use_blue_noise_dithering, simulator_objects::use_blue_noise_dithering); glUniform1f(cloud_map_scale, simulator_objects::cloud_map_scale); glUniform1f(base_noise_scale, simulator_objects::base_noise_scale); glUniform1f(detail_noise_scale, simulator_objects::detail_noise_scale); glUniform1f(blue_noise_scale, simulator_objects::blue_noise_scale); glUniform1iv(cloud_types, CLOUD_LAYER_COUNT, simulator_objects::cloud_types); glUniform1fv(cloud_bases, CLOUD_LAYER_COUNT, simulator_objects::cloud_bases); glUniform1fv(cloud_tops, CLOUD_LAYER_COUNT, simulator_objects::cloud_tops); glUniform1fv(cloud_coverages, CLOUD_TYPE_COUNT, simulator_objects::cloud_coverages); glUniform1fv(cloud_densities, CLOUD_TYPE_COUNT, simulator_objects::cloud_densities); glUniform3fv(base_noise_ratios, CLOUD_TYPE_COUNT, reinterpret_cast<GLfloat*>(simulator_objects::base_noise_ratios)); glUniform3fv(detail_noise_ratios, CLOUD_TYPE_COUNT, reinterpret_cast<GLfloat*>(simulator_objects::detail_noise_ratios)); glUniform3fv(wind_offsets, CLOUD_LAYER_COUNT, reinterpret_cast<GLfloat*>(simulator_objects::wind_offsets)); glUniform1f(base_anvil, simulator_objects::base_anvil); glUniform1f(top_anvil, simulator_objects::top_anvil); glUniform1f(fade_start_distance, simulator_objects::fade_start_distance); glUniform1f(fade_end_distance, simulator_objects::fade_end_distance); glUniform1f(light_attenuation, simulator_objects::light_attenuation); glUniform3fv(sun_direction, 1, glm::value_ptr(simulator_objects::sun_direction)); glUniform3fv(sun_tint, 1, glm::value_ptr(simulator_objects::sun_tint)); glUniform1f(sun_gain, simulator_objects::sun_gain); glUniform3fv(ambient_tint, 1, glm::value_ptr(simulator_objects::ambient_tint)); glUniform1f(ambient_gain, simulator_objects::ambient_gain); glUniform1f(mie_scattering, simulator_objects::mie_scattering); glUniform3fv(atmosphere_bottom_tint, 1, glm::value_ptr(simulator_objects::atmosphere_bottom_tint)); glUniform3fv(atmosphere_top_tint, 1, glm::value_ptr(simulator_objects::atmosphere_top_tint)); glUniform1f(atmospheric_blending, simulator_objects::atmospheric_blending); glDrawArrays(GL_TRIANGLES, 0, 6); XPLMBindTexture2d(EMPTY_OBJECT, 0); XPLMBindTexture2d(EMPTY_OBJECT, 1); XPLMBindTexture2d(EMPTY_OBJECT, 2); XPLMBindTexture2d(EMPTY_OBJECT, 3); XPLMBindTexture2d(EMPTY_OBJECT, 4); XPLMBindTexture2d(EMPTY_OBJECT, 5); XPLMBindTexture2d(EMPTY_OBJECT, 6); XPLMBindTexture2d(EMPTY_OBJECT, 7); XPLMBindTexture2d(EMPTY_OBJECT, 8); glUseProgram(EMPTY_OBJECT); glBindVertexArray(EMPTY_OBJECT); glViewport(simulator_objects::current_viewport.x, simulator_objects::current_viewport.y, simulator_objects::current_viewport.z, simulator_objects::current_viewport.w); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, previous_framebuffer); } }
10,832
C++
.cpp
192
53.166667
169
0.793503
FarukEroglu2048/Enhanced-Cloudscapes
34
12
2
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,758
simulator_objects.cpp
FarukEroglu2048_Enhanced-Cloudscapes/src/simulator_objects.cpp
#include <simulator_objects.hpp> #include <dataref_helpers.hpp> #include <glm/common.hpp> #include <glm/matrix.hpp> #include <glm/trigonometric.hpp> #include <glm/gtc/type_ptr.hpp> #include <XPLMDisplay.h> #define WIND_LAYER_COUNT 3 #define MPS_PER_KNOTS 0.514444444f namespace simulator_objects { XPLMDataRef current_eye_dataref; XPLMDataRef viewport_dataref; XPLMDataRef rendering_resolution_ratio_dataref; XPLMDataRef reverse_z_dataref; XPLMDataRef modelview_matrix_dataref; XPLMDataRef projection_matrix_dataref; XPLMDataRef skip_fragments_dataref; XPLMDataRef sample_step_count_dataref; XPLMDataRef sun_step_count_dataref; XPLMDataRef maximum_sample_step_size_dataref; XPLMDataRef maximum_sun_step_size_dataref; XPLMDataRef use_blue_noise_dithering_dataref; XPLMDataRef cloud_map_scale_dataref; XPLMDataRef base_noise_scale_dataref; XPLMDataRef detail_noise_scale_dataref; XPLMDataRef blue_noise_scale_dataref; XPLMDataRef cloud_type_datarefs[CLOUD_LAYER_COUNT]; XPLMDataRef cloud_base_datarefs[CLOUD_LAYER_COUNT]; XPLMDataRef cloud_top_datarefs[CLOUD_TYPE_COUNT]; XPLMDataRef cloud_coverage_datarefs[CLOUD_TYPE_COUNT]; XPLMDataRef cloud_density_datarefs[CLOUD_TYPE_COUNT]; XPLMDataRef base_noise_ratio_datarefs[CLOUD_TYPE_COUNT]; XPLMDataRef detail_noise_ratio_datarefs[CLOUD_TYPE_COUNT]; XPLMDataRef wind_altitude_datarefs[WIND_LAYER_COUNT]; XPLMDataRef wind_direction_datarefs[WIND_LAYER_COUNT]; XPLMDataRef wind_speed_datarefs[WIND_LAYER_COUNT]; XPLMDataRef zulu_time_dataref; XPLMDataRef base_anvil_dataref; XPLMDataRef top_anvil_dataref; XPLMDataRef fade_start_distance_dataref; XPLMDataRef fade_end_distance_dataref; XPLMDataRef light_attenuation_dataref; XPLMDataRef sun_pitch_dataref; XPLMDataRef sun_heading_dataref; XPLMDataRef sun_tint_red_dataref; XPLMDataRef sun_tint_green_dataref; XPLMDataRef sun_tint_blue_dataref; XPLMDataRef sun_gain_dataref; XPLMDataRef ambient_tint_red_dataref; XPLMDataRef ambient_tint_green_dataref; XPLMDataRef ambient_tint_blue_dataref; XPLMDataRef ambient_gain_dataref; XPLMDataRef mie_scattering_dataref; XPLMDataRef atmosphere_bottom_tint_dataref; XPLMDataRef atmosphere_top_tint_dataref; XPLMDataRef atmospheric_blending_dataref; glm::ivec4 previous_viewport; glm::ivec4 current_viewport; glm::ivec2 previous_rendering_resolution; glm::ivec2 current_rendering_resolution; int reverse_z; float near_clip_z; float far_clip_z; glm::dmat4 previous_mvp_matrix; glm::dmat4 current_mvp_matrix; glm::dmat4 inverse_modelview_matrix; glm::dmat4 inverse_projection_matrix; int skip_fragments; int frame_index; int sample_step_count; int sun_step_count; float maximum_sample_step_size; float maximum_sun_step_size; int use_blue_noise_dithering; float cloud_map_scale; float base_noise_scale; float detail_noise_scale; float blue_noise_scale; int cloud_types[CLOUD_LAYER_COUNT]; float cloud_bases[CLOUD_LAYER_COUNT]; float cloud_tops[CLOUD_LAYER_COUNT]; float cloud_coverages[CLOUD_TYPE_COUNT]; float cloud_densities[CLOUD_TYPE_COUNT]; glm::vec3 base_noise_ratios[CLOUD_TYPE_COUNT]; glm::vec3 detail_noise_ratios[CLOUD_TYPE_COUNT]; glm::vec3 wind_offsets[CLOUD_LAYER_COUNT]; float base_anvil; float top_anvil; float fade_start_distance; float fade_end_distance; float light_attenuation; glm::vec3 sun_direction; glm::vec3 sun_tint; float sun_gain; glm::vec3 ambient_tint; float ambient_gain; float mie_scattering; glm::vec3 atmosphere_bottom_tint; glm::vec3 atmosphere_top_tint; float atmospheric_blending; float previous_zulu_time; float current_zulu_time; void initialize() { XPLMDataRef override_clouds_dataref = XPLMFindDataRef("sim/operation/override/override_clouds"); XPLMSetDatai(override_clouds_dataref, 1); current_eye_dataref = XPLMFindDataRef("sim/graphics/view/draw_call_type"); viewport_dataref = XPLMFindDataRef("sim/graphics/view/viewport"); rendering_resolution_ratio_dataref = export_float_dataref("enhanced_cloudscapes/rendering_resolution_ratio", 0.7); reverse_z_dataref = XPLMFindDataRef("sim/graphics/view/is_reverse_float_z"); modelview_matrix_dataref = XPLMFindDataRef("sim/graphics/view/world_matrix"); projection_matrix_dataref = XPLMFindDataRef("sim/graphics/view/projection_matrix"); skip_fragments_dataref = export_int_dataref("enhanced_cloudscapes/skip_fragments", 0); sample_step_count_dataref = export_int_dataref("enhanced_cloudscapes/sample_step_count", 64); sun_step_count_dataref = export_int_dataref("enhanced_cloudscapes/sun_step_count", 6); maximum_sample_step_size_dataref = export_float_dataref("enhanced_cloudscapes/maximum_sample_step_size", 100.0f); maximum_sun_step_size_dataref = export_float_dataref("enhanced_cloudscapes/maximum_sun_step_size", 1000.0f); use_blue_noise_dithering_dataref = export_int_dataref("enhanced_cloudscapes/use_blue_noise_dithering", 1); cloud_map_scale_dataref = export_float_dataref("enhanced_cloudscapes/cloud_map_scale", 0.0000125f); base_noise_scale_dataref = export_float_dataref("enhanced_cloudscapes/base_noise_scale", 0.0000325f); detail_noise_scale_dataref = export_float_dataref("enhanced_cloudscapes/detail_noise_scale", 0.000325f); blue_noise_scale_dataref = export_float_dataref("enhanced_cloudscapes/blue_noise_scale", 0.01f); cloud_type_datarefs[0] = XPLMFindDataRef("sim/weather/cloud_coverage[0]"); cloud_type_datarefs[1] = XPLMFindDataRef("sim/weather/cloud_coverage[1]"); cloud_type_datarefs[2] = XPLMFindDataRef("sim/weather/cloud_coverage[2]"); cloud_base_datarefs[0] = XPLMFindDataRef("sim/weather/cloud_base_msl_m[0]"); cloud_base_datarefs[1] = XPLMFindDataRef("sim/weather/cloud_base_msl_m[1]"); cloud_base_datarefs[2] = XPLMFindDataRef("sim/weather/cloud_base_msl_m[2]"); cloud_top_datarefs[0] = XPLMFindDataRef("sim/weather/cloud_tops_msl_m[0]"); cloud_top_datarefs[1] = XPLMFindDataRef("sim/weather/cloud_tops_msl_m[1]"); cloud_top_datarefs[2] = XPLMFindDataRef("sim/weather/cloud_tops_msl_m[2]"); cloud_coverage_datarefs[0] = export_float_dataref("enhanced_cloudscapes/cirrus/coverage", 0.85f); cloud_coverage_datarefs[1] = export_float_dataref("enhanced_cloudscapes/few/coverage", 0.05f); cloud_coverage_datarefs[2] = export_float_dataref("enhanced_cloudscapes/scattered/coverage", 0.25f); cloud_coverage_datarefs[3] = export_float_dataref("enhanced_cloudscapes/broken/coverage", 0.5f); cloud_coverage_datarefs[4] = export_float_dataref("enhanced_cloudscapes/overcast/coverage", 0.75f); cloud_coverage_datarefs[5] = export_float_dataref("enhanced_cloudscapes/stratus/coverage", 1.0f); cloud_density_datarefs[0] = export_float_dataref("enhanced_cloudscapes/cirrus/density", 0.0015f); cloud_density_datarefs[1] = export_float_dataref("enhanced_cloudscapes/few/density", 0.0015f); cloud_density_datarefs[2] = export_float_dataref("enhanced_cloudscapes/scattered/density", 0.0015f); cloud_density_datarefs[3] = export_float_dataref("enhanced_cloudscapes/broken/density", 0.002f); cloud_density_datarefs[4] = export_float_dataref("enhanced_cloudscapes/overcast/density", 0.002f); cloud_density_datarefs[5] = export_float_dataref("enhanced_cloudscapes/stratus/density", 0.0025f); base_noise_ratio_datarefs[0] = export_vec3_dataref("enhanced_cloudscapes/cirrus/base_noise_ratios", glm::vec3(0.625f, 0.25f, 0.125f)); base_noise_ratio_datarefs[1] = export_vec3_dataref("enhanced_cloudscapes/few/base_noise_ratios", glm::vec3(0.625f, 0.25f, 0.125f)); base_noise_ratio_datarefs[2] = export_vec3_dataref("enhanced_cloudscapes/scattered/base_noise_ratios", glm::vec3(0.625f, 0.25f, 0.125f)); base_noise_ratio_datarefs[3] = export_vec3_dataref("enhanced_cloudscapes/broken/base_noise_ratios", glm::vec3(0.625f, 0.25f, 0.125f)); base_noise_ratio_datarefs[4] = export_vec3_dataref("enhanced_cloudscapes/overcast/base_noise_ratios", glm::vec3(0.625f, 0.25f, 0.125f)); base_noise_ratio_datarefs[5] = export_vec3_dataref("enhanced_cloudscapes/stratus/base_noise_ratios", glm::vec3(0.625f, 0.25f, 0.125f)); detail_noise_ratio_datarefs[0] = export_vec3_dataref("enhanced_cloudscapes/cirrus/detail_noise_ratios", glm::vec3(0.25f, 0.125f, 0.0625f)); detail_noise_ratio_datarefs[1] = export_vec3_dataref("enhanced_cloudscapes/few/detail_noise_ratios", glm::vec3(0.625f, 0.25f, 0.125f)); detail_noise_ratio_datarefs[2] = export_vec3_dataref("enhanced_cloudscapes/scattered/detail_noise_ratios", glm::vec3(0.625f, 0.25f, 0.125f)); detail_noise_ratio_datarefs[3] = export_vec3_dataref("enhanced_cloudscapes/broken/detail_noise_ratios", glm::vec3(0.625f, 0.25f, 0.125f)); detail_noise_ratio_datarefs[4] = export_vec3_dataref("enhanced_cloudscapes/overcast/detail_noise_ratios", glm::vec3(0.625f, 0.25f, 0.125f)); detail_noise_ratio_datarefs[5] = export_vec3_dataref("enhanced_cloudscapes/stratus/detail_noise_ratios", glm::vec3(0.625f, 0.25f, 0.125f)); wind_altitude_datarefs[0] = XPLMFindDataRef("sim/weather/wind_altitude_msl_m[0]"); wind_altitude_datarefs[1] = XPLMFindDataRef("sim/weather/wind_altitude_msl_m[1]"); wind_altitude_datarefs[2] = XPLMFindDataRef("sim/weather/wind_altitude_msl_m[2]"); wind_direction_datarefs[0] = XPLMFindDataRef("sim/weather/wind_direction_degt[0]"); wind_direction_datarefs[1] = XPLMFindDataRef("sim/weather/wind_direction_degt[1]"); wind_direction_datarefs[2] = XPLMFindDataRef("sim/weather/wind_direction_degt[2]"); wind_speed_datarefs[0] = XPLMFindDataRef("sim/weather/wind_speed_kt[0]"); wind_speed_datarefs[1] = XPLMFindDataRef("sim/weather/wind_speed_kt[1]"); wind_speed_datarefs[2] = XPLMFindDataRef("sim/weather/wind_speed_kt[2]"); zulu_time_dataref = XPLMFindDataRef("sim/time/zulu_time_sec"); base_anvil_dataref = export_float_dataref("enhanced_cloudscapes/base_anvil", 2.5f); top_anvil_dataref = export_float_dataref("enhanced_cloudscapes/top_anvil", 1.0f); light_attenuation_dataref = export_float_dataref("enhanced_cloudscapes/light_attenuation", 2.25f); sun_pitch_dataref = XPLMFindDataRef("sim/graphics/scenery/sun_pitch_degrees"); sun_heading_dataref = XPLMFindDataRef("sim/graphics/scenery/sun_heading_degrees"); sun_gain_dataref = export_float_dataref("enhanced_cloudscapes/sun_gain", 10.0f); ambient_tint_red_dataref = XPLMFindDataRef("sim/graphics/misc/outside_light_level_r"); ambient_tint_green_dataref = XPLMFindDataRef("sim/graphics/misc/outside_light_level_g"); ambient_tint_blue_dataref = XPLMFindDataRef("sim/graphics/misc/outside_light_level_b"); ambient_gain_dataref = export_float_dataref("enhanced_cloudscapes/ambient_gain", 0.95f); mie_scattering_dataref = export_float_dataref("enhanced_cloudscapes/mie_scattering", 0.85f); atmosphere_bottom_tint_dataref = export_vec3_dataref("enhanced_cloudscapes/atmosphere_bottom_tint", glm::vec3(0.55f, 0.775f, 1.0f)); atmosphere_top_tint_dataref = export_vec3_dataref("enhanced_cloudscapes/atmosphere_top_tint", glm::vec3(0.45f, 0.675f, 1.0f)); atmospheric_blending_dataref = export_float_dataref("enhanced_cloudscapes/atmospheric_blending", 0.325f); } void update() { XPLMDataRef fog_clip_scale_dataref = XPLMFindDataRef("sim/private/controls/terrain/fog_clip_scale"); XPLMSetDataf(fog_clip_scale_dataref, -400.0); int eye_index = XPLMGetDatai(current_eye_dataref); previous_viewport = current_viewport; XPLMGetDatavi(viewport_dataref, glm::value_ptr(current_viewport), 0, current_viewport.length()); current_viewport.z -= current_viewport.x; current_viewport.w -= current_viewport.y; if (eye_index == 4) current_viewport.x += current_viewport.z; int screen_width; int screen_height; XPLMGetScreenSize(&screen_width, &screen_height); float rendering_resolution_ratio = XPLMGetDataf(rendering_resolution_ratio_dataref); previous_rendering_resolution = current_rendering_resolution; current_rendering_resolution = glm::ivec2(screen_width * rendering_resolution_ratio, screen_height * rendering_resolution_ratio); reverse_z = XPLMGetDatai(reverse_z_dataref); if (reverse_z == 0) { near_clip_z = -1.0; far_clip_z = 1.0; } else { near_clip_z = 1.0; far_clip_z = 0.0; } glm::mat4 float_modelview_matrix; glm::mat4 float_projection_matrix; XPLMGetDatavf(modelview_matrix_dataref, glm::value_ptr(float_modelview_matrix), 0, float_modelview_matrix.length() * float_modelview_matrix.length()); XPLMGetDatavf(projection_matrix_dataref, glm::value_ptr(float_projection_matrix), 0, float_projection_matrix.length() * float_projection_matrix.length()); glm::dmat4 double_modelview_matrix = glm::dmat4(float_modelview_matrix); glm::dmat4 double_projection_matrix = glm::dmat4(float_projection_matrix); previous_mvp_matrix = current_mvp_matrix; current_mvp_matrix = double_projection_matrix * double_modelview_matrix; inverse_modelview_matrix = glm::inverse(double_modelview_matrix); inverse_projection_matrix = glm::inverse(double_projection_matrix); if ((eye_index == 3) || (eye_index == 4)) skip_fragments = 0; else skip_fragments = XPLMGetDatai(skip_fragments_dataref); frame_index++; sample_step_count = XPLMGetDatai(sample_step_count_dataref); sun_step_count = XPLMGetDatai(sun_step_count_dataref); maximum_sample_step_size = XPLMGetDataf(maximum_sample_step_size_dataref); maximum_sun_step_size = XPLMGetDataf(maximum_sun_step_size_dataref); use_blue_noise_dithering = XPLMGetDatai(use_blue_noise_dithering_dataref); cloud_map_scale = XPLMGetDataf(cloud_map_scale_dataref); base_noise_scale = XPLMGetDataf(base_noise_scale_dataref); detail_noise_scale = XPLMGetDataf(detail_noise_scale_dataref); blue_noise_scale = XPLMGetDataf(blue_noise_scale_dataref); for (int layer_index = 0; layer_index < CLOUD_LAYER_COUNT; layer_index++) cloud_types[layer_index] = static_cast<int>(XPLMGetDataf(cloud_type_datarefs[layer_index])); for (int layer_index = 0; layer_index < CLOUD_LAYER_COUNT; layer_index++) { cloud_bases[layer_index] = XPLMGetDataf(cloud_base_datarefs[layer_index]); float new_height; if (cloud_types[layer_index] == 1) new_height = 125.0; else new_height = glm::max((XPLMGetDataf(cloud_top_datarefs[layer_index]) - cloud_bases[layer_index]) * 1.25f, 3250.0f); cloud_tops[layer_index] = cloud_bases[layer_index] + new_height; } for (int type_index = 0; type_index < CLOUD_TYPE_COUNT; type_index++) { cloud_coverages[type_index] = XPLMGetDataf(cloud_coverage_datarefs[type_index]); cloud_densities[type_index] = XPLMGetDataf(cloud_density_datarefs[type_index]); } for (int type_index = 0; type_index < CLOUD_TYPE_COUNT; type_index++) { XPLMGetDatavf(base_noise_ratio_datarefs[type_index], glm::value_ptr(base_noise_ratios[type_index]), 0, base_noise_ratios[type_index].length()); XPLMGetDatavf(detail_noise_ratio_datarefs[type_index], glm::value_ptr(detail_noise_ratios[type_index]), 0, detail_noise_ratios[type_index].length()); } float wind_altitudes[WIND_LAYER_COUNT]; glm::vec3 wind_vectors[WIND_LAYER_COUNT]; for (int layer_index = 0; layer_index < WIND_LAYER_COUNT; layer_index++) { wind_altitudes[layer_index] = XPLMGetDataf(wind_altitude_datarefs[layer_index]); float wind_heading = glm::radians(XPLMGetDataf(wind_direction_datarefs[layer_index])); wind_vectors[layer_index] = glm::vec3(glm::sin(wind_heading), 0.0f, -1.0f * glm::cos(wind_heading)) * XPLMGetDataf(wind_speed_datarefs[layer_index]) * MPS_PER_KNOTS; } previous_zulu_time = current_zulu_time; current_zulu_time = XPLMGetDataf(zulu_time_dataref); float time_difference = current_zulu_time - previous_zulu_time; if (glm::abs(time_difference) > 5.0) time_difference = 0.0; for (int cloud_layer_index = 0; cloud_layer_index < CLOUD_LAYER_COUNT; cloud_layer_index++) { for (int wind_layer_index = 0; wind_layer_index < WIND_LAYER_COUNT; wind_layer_index++) wind_offsets[cloud_layer_index] += wind_vectors[wind_layer_index] * glm::clamp(glm::pow(glm::abs(cloud_bases[cloud_layer_index] - wind_altitudes[wind_layer_index]) * 0.001f, 2.0f), 0.0f, 1.0f) * time_difference; wind_offsets[cloud_layer_index].y += 0.05 * time_difference; } base_anvil = XPLMGetDataf(base_anvil_dataref); top_anvil = XPLMGetDataf(top_anvil_dataref); XPLMDataRef fade_start_distance_dataref = XPLMFindDataRef("sim/private/stats/skyc/fog/near_fog_cld"); XPLMDataRef fade_end_distance_dataref = XPLMFindDataRef("sim/private/stats/skyc/fog/far_fog_cld"); fade_start_distance = XPLMGetDataf(fade_start_distance_dataref); fade_end_distance = XPLMGetDataf(fade_end_distance_dataref); light_attenuation = XPLMGetDataf(light_attenuation_dataref); float sun_pitch = glm::radians(XPLMGetDataf(sun_pitch_dataref)); float sun_heading = glm::radians(XPLMGetDataf(sun_heading_dataref)); sun_direction = glm::vec3(glm::cos(sun_pitch) * glm::sin(sun_heading), glm::sin(sun_pitch), -1.0f * glm::cos(sun_pitch) * glm::cos(sun_heading)); sun_tint_red_dataref = XPLMFindDataRef("sim/private/stats/skyc/sun_dir_r"); sun_tint_green_dataref = XPLMFindDataRef("sim/private/stats/skyc/sun_dir_g"); sun_tint_blue_dataref = XPLMFindDataRef("sim/private/stats/skyc/sun_dir_b"); sun_tint = glm::vec3(XPLMGetDataf(sun_tint_red_dataref), XPLMGetDataf(sun_tint_green_dataref), XPLMGetDataf(sun_tint_blue_dataref)); sun_gain = XPLMGetDataf(sun_gain_dataref); ambient_tint = glm::vec3(XPLMGetDataf(ambient_tint_red_dataref), XPLMGetDataf(ambient_tint_green_dataref), XPLMGetDataf(ambient_tint_blue_dataref)); ambient_gain = XPLMGetDataf(ambient_gain_dataref); mie_scattering = XPLMGetDataf(mie_scattering_dataref); XPLMGetDatavf(atmosphere_bottom_tint_dataref, glm::value_ptr(atmosphere_bottom_tint), 0, atmosphere_bottom_tint.length()); XPLMGetDatavf(atmosphere_top_tint_dataref, glm::value_ptr(atmosphere_top_tint), 0, atmosphere_top_tint.length()); atmospheric_blending = XPLMGetDataf(atmospheric_blending_dataref); } }
17,969
C++
.cpp
289
59.020761
302
0.77035
FarukEroglu2048/Enhanced-Cloudscapes
34
12
2
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,759
post_processing_program.cpp
FarukEroglu2048_Enhanced-Cloudscapes/src/post_processing_program.cpp
#include <post_processing_program.hpp> #include <opengl_helpers.hpp> #include <simulator_objects.hpp> #include <plugin_objects.hpp> #include <XPLMGraphics.h> namespace post_processing_program { GLuint reference; GLint near_clip_z; void initialize() { GLuint vertex_shader = load_shader("Resources/plugins/Enhanced Cloudscapes/shaders/post_processing/vertex_shader.glsl", GL_VERTEX_SHADER); GLuint fragment_shader = load_shader("Resources/plugins/Enhanced Cloudscapes/shaders/post_processing/fragment_shader.glsl", GL_FRAGMENT_SHADER); reference = create_program(vertex_shader, fragment_shader); glUseProgram(reference); GLint current_rendering_texture = glGetUniformLocation(reference, "current_rendering_texture"); glUniform1i(current_rendering_texture, 0); near_clip_z = glGetUniformLocation(reference, "near_clip_z"); glUseProgram(EMPTY_OBJECT); } void call() { XPLMSetGraphicsState(0, 1, 0, 0, 1, 0, 0); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBindVertexArray(plugin_objects::vertex_array); glUseProgram(reference); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, plugin_objects::current_rendering_texture); glUniform1f(near_clip_z, simulator_objects::near_clip_z); glDrawArrays(GL_TRIANGLES, 0, 6); XPLMBindTexture2d(EMPTY_OBJECT, 0); glUseProgram(EMPTY_OBJECT); glBindVertexArray(EMPTY_OBJECT); glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); } }
1,485
C++
.cpp
36
38.444444
146
0.785615
FarukEroglu2048/Enhanced-Cloudscapes
34
12
2
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,760
plugin_objects.cpp
FarukEroglu2048_Enhanced-Cloudscapes/src/plugin_objects.cpp
#include <plugin_objects.hpp> #include <opengl_helpers.hpp> #include <XPLMGraphics.h> namespace plugin_objects { int previous_depth_texture; int current_depth_texture; int cloud_map_textures[CLOUD_LAYER_COUNT]; int base_noise_texture; int detail_noise_texture; int blue_noise_texture; int previous_rendering_texture; int current_rendering_texture; GLuint framebuffer; GLuint vertex_array; void initialize() { previous_depth_texture = create_fullscreen_texture(); current_depth_texture = create_fullscreen_texture(); cloud_map_textures[0] = load_png_texture("Resources/plugins/Enhanced Cloudscapes/textures/cloud_map_1.png", false); cloud_map_textures[1] = load_png_texture("Resources/plugins/Enhanced Cloudscapes/textures/cloud_map_2.png", false); cloud_map_textures[2] = load_png_texture("Resources/plugins/Enhanced Cloudscapes/textures/cloud_map_3.png", false); base_noise_texture = load_png_texture("Resources/plugins/Enhanced Cloudscapes/textures/base_noise.png", true); detail_noise_texture = load_png_texture("Resources/plugins/Enhanced Cloudscapes/textures/detail_noise.png", true); blue_noise_texture = load_png_texture("Resources/plugins/Enhanced Cloudscapes/textures/blue_noise.png", false); previous_rendering_texture = create_fullscreen_texture(); current_rendering_texture = create_fullscreen_texture(); GLint previous_framebuffer; glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &previous_framebuffer); glGenFramebuffers(1, &framebuffer); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, framebuffer); glFramebufferTexture(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, current_rendering_texture, 0); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, previous_framebuffer); glGenVertexArrays(1, &vertex_array); glBindVertexArray(vertex_array); GLuint vertex_buffer; glGenBuffers(1, &vertex_buffer); glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer); GLfloat quad_vertices[] = { -1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0 }; glBufferData(GL_ARRAY_BUFFER, sizeof(quad_vertices), quad_vertices, GL_STATIC_DRAW); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, EMPTY_OBJECT); glBindVertexArray(EMPTY_OBJECT); } void update() { XPLMSetGraphicsState(0, 1, 0, 0, 0, 0, 0); glActiveTexture(GL_TEXTURE0); if ((simulator_objects::current_viewport.z != simulator_objects::previous_viewport.z) || (simulator_objects::current_viewport.w != simulator_objects::previous_viewport.w)) { GLenum depth_format; if (simulator_objects::reverse_z == 0) depth_format = GL_DEPTH_COMPONENT24; else depth_format = GL_DEPTH_COMPONENT32F; glBindTexture(GL_TEXTURE_2D, previous_depth_texture); glTexImage2D(GL_TEXTURE_2D, 0, depth_format, simulator_objects::current_viewport.z, simulator_objects::current_viewport.w, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, nullptr); glCopyImageSubData(current_depth_texture, GL_TEXTURE_2D, 0, 0, 0, 0, previous_depth_texture, GL_TEXTURE_2D, 0, 0, 0, 0, simulator_objects::current_viewport.z, simulator_objects::current_viewport.w, 1); glBindTexture(GL_TEXTURE_2D, current_depth_texture); glCopyTexImage2D(GL_TEXTURE_2D, 0, depth_format, simulator_objects::current_viewport.x, simulator_objects::current_viewport.y, simulator_objects::current_viewport.z, simulator_objects::current_viewport.w, 0); } else { glCopyImageSubData(current_depth_texture, GL_TEXTURE_2D, 0, 0, 0, 0, previous_depth_texture, GL_TEXTURE_2D, 0, 0, 0, 0, simulator_objects::current_viewport.z, simulator_objects::current_viewport.w, 1); glBindTexture(GL_TEXTURE_2D, current_depth_texture); glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, simulator_objects::current_viewport.x, simulator_objects::current_viewport.y, simulator_objects::current_viewport.z, simulator_objects::current_viewport.w); } if ((simulator_objects::current_rendering_resolution.x != simulator_objects::previous_rendering_resolution.x) || (simulator_objects::current_rendering_resolution.y != simulator_objects::previous_rendering_resolution.y)) { glBindTexture(GL_TEXTURE_2D, previous_rendering_texture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, simulator_objects::current_rendering_resolution.x, simulator_objects::current_rendering_resolution.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); glCopyImageSubData(current_rendering_texture, GL_TEXTURE_2D, 0, 0, 0, 0, previous_rendering_texture, GL_TEXTURE_2D, 0, 0, 0, 0, simulator_objects::current_rendering_resolution.x, simulator_objects::current_rendering_resolution.y, 1); glBindTexture(GL_TEXTURE_2D, current_rendering_texture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, simulator_objects::current_rendering_resolution.x, simulator_objects::current_rendering_resolution.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); } else glCopyImageSubData(current_rendering_texture, GL_TEXTURE_2D, 0, 0, 0, 0, previous_rendering_texture, GL_TEXTURE_2D, 0, 0, 0, 0, simulator_objects::current_rendering_resolution.x, simulator_objects::current_rendering_resolution.y, 1); XPLMBindTexture2d(EMPTY_OBJECT, 0); } }
5,161
C++
.cpp
86
56.662791
240
0.769796
FarukEroglu2048/Enhanced-Cloudscapes
34
12
2
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,761
opengl_helpers.cpp
FarukEroglu2048_Enhanced-Cloudscapes/src/opengl_helpers.cpp
#include <opengl_helpers.hpp> #include <XPLMUtilities.h> #include <XPLMGraphics.h> #include <png.h> #include <fstream> void read_stream_callback(png_structp png_struct, png_bytep output_data, png_size_t read_size) { png_voidp stream_pointer = png_get_io_ptr(png_struct); std::ifstream& input_stream = *static_cast<std::ifstream*>(stream_pointer); input_stream.read(reinterpret_cast<char*>(output_data), read_size); } png_size_t get_bytes_per_pixel(png_byte color_type) { switch (color_type) { case PNG_COLOR_TYPE_GRAY: return 1; case PNG_COLOR_TYPE_GRAY_ALPHA: return 2; case PNG_COLOR_TYPE_RGB: return 3; case PNG_COLOR_TYPE_RGB_ALPHA: return 4; } } GLenum get_texture_format(png_byte color_type) { switch (color_type) { case PNG_COLOR_TYPE_GRAY: return GL_RED; case PNG_COLOR_TYPE_GRAY_ALPHA: return GL_RG; case PNG_COLOR_TYPE_RGB: return GL_RGB; case PNG_COLOR_TYPE_RGB_ALPHA: return GL_RGBA; } } png_size_t integer_square_root(png_size_t input_value) { png_size_t square_root = 0; while ((square_root * square_root) < input_value) square_root++; return square_root; } int create_fullscreen_texture() { int texture_reference; XPLMGenerateTextureNumbers(&texture_reference, 1); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture_reference); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); XPLMBindTexture2d(EMPTY_OBJECT, 0); return texture_reference; } int create_texture(GLsizei texture_width, GLsizei texture_height, GLenum data_format, const void* texture_data) { int texture_reference; XPLMGenerateTextureNumbers(&texture_reference, 1); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture_reference); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, data_format, texture_width, texture_height, 0, data_format, GL_UNSIGNED_BYTE, texture_data); XPLMBindTexture2d(EMPTY_OBJECT, 0); return texture_reference; } int create_texture(GLsizei texture_width, GLsizei texture_height, GLsizei texture_depth, GLenum data_format, const void* texture_data) { int texture_reference; XPLMGenerateTextureNumbers(&texture_reference, 1); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_3D, texture_reference); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage3D(GL_TEXTURE_3D, 0, data_format, texture_width, texture_height, texture_depth, 0, data_format, GL_UNSIGNED_BYTE, texture_data); XPLMBindTexture2d(EMPTY_OBJECT, 0); return texture_reference; } int load_png_texture(const char* texture_path, bool add_depth) { int output_texture = EMPTY_OBJECT; std::ifstream texture_file(texture_path, std::ifstream::binary); if (texture_file.fail() == false) { png_structp png_struct = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr); png_infop png_info = png_create_info_struct(png_struct); png_set_read_fn(png_struct, &texture_file, read_stream_callback); png_read_info(png_struct, png_info); png_set_scale_16(png_struct); png_set_expand(png_struct); png_byte color_type = png_get_color_type(png_struct, png_info); png_size_t bytes_per_pixel = get_bytes_per_pixel(color_type); png_uint_32 image_width = png_get_image_width(png_struct, png_info); png_uint_32 image_height = png_get_image_height(png_struct, png_info); png_bytep texture_data = new png_byte[image_height * image_width * bytes_per_pixel]; png_bytepp texture_row_pointers = new png_bytep[image_height]; for (png_size_t row_index = 0; row_index < image_height; row_index++) texture_row_pointers[row_index] = &texture_data[row_index * image_width * bytes_per_pixel]; png_read_image(png_struct, texture_row_pointers); if (add_depth == true) output_texture = create_texture(image_width, integer_square_root(image_height), integer_square_root(image_height), get_texture_format(color_type), texture_data); else output_texture = create_texture(image_width, image_height, get_texture_format(color_type), texture_data); delete[] texture_row_pointers; delete[] texture_data; png_destroy_read_struct(&png_struct, &png_info, nullptr); } else { XPLMDebugString("Could not open texture file!"); XPLMDebugString("Texture file path is:"); XPLMDebugString(texture_path); } return output_texture; } GLuint load_shader(const char* shader_path, GLenum shader_type) { GLuint output_shader = EMPTY_OBJECT; std::ifstream shader_file(shader_path, std::ifstream::binary | std::ifstream::ate); if (shader_file.fail() == false) { GLint shader_file_size = shader_file.tellg(); shader_file.seekg(0); GLchar* shader_string = new GLchar[shader_file_size]; shader_file.read(shader_string, shader_file_size); GLuint shader_reference = glCreateShader(shader_type); glShaderSource(shader_reference, 1, &shader_string, &shader_file_size); glCompileShader(shader_reference); delete[] shader_string; GLint shader_compilation_status; glGetShaderiv(shader_reference, GL_COMPILE_STATUS, &shader_compilation_status); if (shader_compilation_status == GL_TRUE) output_shader = shader_reference; else { GLint compilation_log_length; glGetShaderiv(shader_reference, GL_INFO_LOG_LENGTH, &compilation_log_length); GLchar* compilation_message = new GLchar[compilation_log_length]; glGetShaderInfoLog(shader_reference, compilation_log_length, nullptr, compilation_message); XPLMDebugString("\nShader compilation failed!\n\n"); XPLMDebugString("Compilation error message is:\n"); XPLMDebugString(compilation_message); delete[] compilation_message; } } else { XPLMDebugString("\nCould not open shader file!\n\n"); XPLMDebugString("Shader file path is:\n"); XPLMDebugString(shader_path); } return output_shader; } GLuint create_program(GLuint vertex_shader, GLuint fragment_shader) { GLuint output_program = EMPTY_OBJECT; GLuint program_reference = glCreateProgram(); glAttachShader(program_reference, vertex_shader); glAttachShader(program_reference, fragment_shader); glLinkProgram(program_reference); GLint program_link_status; glGetProgramiv(program_reference, GL_LINK_STATUS, &program_link_status); if (program_link_status == GL_TRUE) output_program = program_reference; else { GLint compilation_log_length; glGetProgramiv(program_reference, GL_INFO_LOG_LENGTH, &compilation_log_length); GLchar* compilation_message = new GLchar[compilation_log_length]; glGetProgramInfoLog(program_reference, compilation_log_length, nullptr, compilation_message); XPLMDebugString("\nProgram compilation failed!\n\n"); XPLMDebugString("Compilation error message is:\n"); XPLMDebugString(compilation_message); delete[] compilation_message; } return output_program; }
6,858
C++
.cpp
172
37.180233
186
0.768092
FarukEroglu2048/Enhanced-Cloudscapes
34
12
2
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,762
enhanced_cloudscapes.cpp
FarukEroglu2048_Enhanced-Cloudscapes/src/enhanced_cloudscapes.cpp
#ifdef IBM #include <Windows.h> #endif #include <GL/glew.h> #include <XPLMDataAccess.h> #include <XPLMDisplay.h> #include <simulator_objects.hpp> #include <plugin_objects.hpp> #include <rendering_program.hpp> #include <post_processing_program.hpp> #include <cstring> #ifdef IBM BOOL APIENTRY DllMain(IN HINSTANCE dll_handle, IN DWORD call_reason, IN LPVOID reserved) { return TRUE; } #endif int draw_callback(XPLMDrawingPhase drawing_phase, int is_before, void* callback_reference) { simulator_objects::update(); plugin_objects::update(); rendering_program::call(); post_processing_program::call(); return 1; } PLUGIN_API int XPluginStart(char* plugin_name, char* plugin_signature, char* plugin_description) { std::strcpy(plugin_name, "Enhanced Cloudscapes"); std::strcpy(plugin_signature, "FarukEroglu2048.enhanced_cloudscapes"); std::strcpy(plugin_description, "Volumetric Clouds for X-Plane 11"); glewInit(); simulator_objects::initialize(); plugin_objects::initialize(); rendering_program::initialize(); post_processing_program::initialize(); XPLMRegisterDrawCallback(draw_callback, xplm_Phase_Modern3D, 0, nullptr); return 1; } PLUGIN_API void XPluginStop(void) { } PLUGIN_API int XPluginEnable(void) { return 1; } PLUGIN_API void XPluginDisable(void) { } PLUGIN_API void XPluginReceiveMessage(XPLMPluginID sender_plugin, int message_type, void* callback_parameters) { }
1,415
C++
.cpp
51
25.980392
110
0.792846
FarukEroglu2048/Enhanced-Cloudscapes
34
12
2
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,763
simulator_objects.hpp
FarukEroglu2048_Enhanced-Cloudscapes/include/simulator_objects.hpp
#pragma once #include <glm/vec3.hpp> #include <glm/vec4.hpp> #include <glm/mat4x4.hpp> #define CLOUD_LAYER_COUNT 3 #define CLOUD_TYPE_COUNT 6 namespace simulator_objects { extern glm::ivec4 previous_viewport; extern glm::ivec4 current_viewport; extern glm::ivec2 previous_rendering_resolution; extern glm::ivec2 current_rendering_resolution; extern int reverse_z; extern float near_clip_z; extern float far_clip_z; extern glm::dmat4 previous_mvp_matrix; extern glm::dmat4 current_mvp_matrix; extern glm::dmat4 inverse_modelview_matrix; extern glm::dmat4 inverse_projection_matrix; extern int skip_fragments; extern int frame_index; extern int sample_step_count; extern int sun_step_count; extern float maximum_sample_step_size; extern float maximum_sun_step_size; extern int use_blue_noise_dithering; extern float cloud_map_scale; extern float base_noise_scale; extern float detail_noise_scale; extern float blue_noise_scale; extern int cloud_types[CLOUD_LAYER_COUNT]; extern float cloud_bases[CLOUD_LAYER_COUNT]; extern float cloud_tops[CLOUD_LAYER_COUNT]; extern float cloud_coverages[CLOUD_TYPE_COUNT]; extern float cloud_densities[CLOUD_TYPE_COUNT]; extern glm::vec3 base_noise_ratios[CLOUD_TYPE_COUNT]; extern glm::vec3 detail_noise_ratios[CLOUD_TYPE_COUNT]; extern glm::vec3 wind_offsets[CLOUD_LAYER_COUNT]; extern float base_anvil; extern float top_anvil; extern float fade_start_distance; extern float fade_end_distance; extern float light_attenuation; extern glm::vec3 sun_direction; extern glm::vec3 sun_tint; extern float sun_gain; extern glm::vec3 ambient_tint; extern float ambient_gain; extern float mie_scattering; extern glm::vec3 atmosphere_bottom_tint; extern glm::vec3 atmosphere_top_tint; extern float atmospheric_blending; void initialize(); void update(); }
1,856
C++
.h
55
31.363636
56
0.800113
FarukEroglu2048/Enhanced-Cloudscapes
34
12
2
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,764
plugin_objects.hpp
FarukEroglu2048_Enhanced-Cloudscapes/include/plugin_objects.hpp
#pragma once #include <simulator_objects.hpp> #include <GL/glew.h> namespace plugin_objects { extern int previous_depth_texture; extern int current_depth_texture; extern int cloud_map_textures[CLOUD_LAYER_COUNT]; extern int base_noise_texture; extern int detail_noise_texture; extern int blue_noise_texture; extern int previous_rendering_texture; extern int current_rendering_texture; extern GLuint framebuffer; extern GLuint vertex_array; void initialize(); void update(); };
497
C++
.h
18
25.5
50
0.808917
FarukEroglu2048/Enhanced-Cloudscapes
34
12
2
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,765
post_processing_program.hpp
FarukEroglu2048_Enhanced-Cloudscapes/include/post_processing_program.hpp
#pragma once namespace post_processing_program { void initialize(); void call(); }
85
C++
.h
6
12.833333
33
0.78481
FarukEroglu2048/Enhanced-Cloudscapes
34
12
2
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,766
rendering_program.hpp
FarukEroglu2048_Enhanced-Cloudscapes/include/rendering_program.hpp
#pragma once namespace rendering_program { void initialize(); void call(); }
79
C++
.h
6
11.833333
27
0.780822
FarukEroglu2048/Enhanced-Cloudscapes
34
12
2
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,767
dataref_helpers.hpp
FarukEroglu2048_Enhanced-Cloudscapes/include/dataref_helpers.hpp
#pragma once #include <XPLMDataAccess.h> #include <glm/vec3.hpp> XPLMDataRef export_int_dataref(char* dataref_name, int initial_value); XPLMDataRef export_float_dataref(char* dataref_name, float initial_value); XPLMDataRef export_vec3_dataref(char* dataref_name, glm::vec3 initial_value);
291
C++
.h
6
47.166667
77
0.809187
FarukEroglu2048/Enhanced-Cloudscapes
34
12
2
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,768
opengl_helpers.hpp
FarukEroglu2048_Enhanced-Cloudscapes/include/opengl_helpers.hpp
#pragma once #include <GL/glew.h> #define EMPTY_OBJECT 0 int create_fullscreen_texture(); int create_texture(GLsizei texture_width, GLsizei texture_height, GLenum data_format, const void* texture_data); int create_texture(GLsizei texture_width, GLsizei texture_height, GLsizei texture_depth, GLenum data_format, const void* texture_data); int load_png_texture(const char* texture_path, bool add_depth); GLuint load_shader(const char* shader_path, GLenum shader_type); GLuint create_program(GLuint vertex_shader, GLuint fragment_shader);
543
C++
.h
9
58.666667
135
0.806818
FarukEroglu2048/Enhanced-Cloudscapes
34
12
2
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,769
demux.cpp
Harekaze_pvr_epgstation/src/pvr_client/demux.cpp
/* * Copyright (C) 2015-2020 Yuki MIZUNO * https://github.com/Harekaze/pvr.epgstation/ * SPDX-License-Identifier: GPL-3.0-only */ #include "kodi/libKODI_guilib.h" #include "kodi/libXBMC_addon.h" #include "kodi/libXBMC_pvr.h" #include <iostream> extern ADDON::CHelper_libXBMC_addon* XBMC; extern CHelper_libXBMC_pvr* PVR; extern "C" { /* not implemented */ void DemuxReset(void) {} void DemuxFlush(void) {} void DemuxAbort(void) {} DemuxPacket* DemuxRead(void) { return nullptr; } }
489
C++
.cpp
18
25.777778
48
0.75
Harekaze/pvr.epgstation
33
6
2
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
1,541,770
stream.cpp
Harekaze_pvr_epgstation/src/pvr_client/stream.cpp
/* * Copyright (C) 2015-2020 Yuki MIZUNO * https://github.com/Harekaze/pvr.epgstation/ * SPDX-License-Identifier: GPL-3.0-only */ #include "kodi/libKODI_guilib.h" #include "kodi/libXBMC_addon.h" #include "kodi/libXBMC_pvr.h" #include <iostream> extern ADDON::CHelper_libXBMC_addon* XBMC; extern CHelper_libXBMC_pvr* PVR; extern "C" { bool CanPauseStream(void) { return false; } bool CanSeekStream(void) { return false; } /* not implemented */ PVR_ERROR SignalStatus(PVR_SIGNAL_STATUS& signalStatus) { return PVR_ERROR_NOT_IMPLEMENTED; } PVR_ERROR GetStreamProperties(PVR_STREAM_PROPERTIES* pProperties) { return PVR_ERROR_NOT_IMPLEMENTED; } PVR_ERROR GetStreamReadChunkSize(int* chunksize) { return PVR_ERROR_NOT_IMPLEMENTED; } void PauseStream(bool bPaused) {} bool SeekTime(int time, bool backwards, double* startpts) { return false; } void SetSpeed(int speed) {} }
885
C++
.cpp
28
30
103
0.7723
Harekaze/pvr.epgstation
33
6
2
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
1,541,771
live.cpp
Harekaze_pvr_epgstation/src/pvr_client/live.cpp
/* * Copyright (C) 2015-2020 Yuki MIZUNO * https://github.com/Harekaze/pvr.epgstation/ * SPDX-License-Identifier: GPL-3.0-only */ #include "epgstation/epgstation.h" #include "epgstation/genre.h" #include "kodi/libKODI_guilib.h" #include "kodi/libXBMC_addon.h" #include "kodi/libXBMC_pvr.h" #include <iostream> extern epgstation::Schedule g_schedule; extern epgstation::Channels g_channels; extern ADDON::CHelper_libXBMC_addon* XBMC; extern CHelper_libXBMC_pvr* PVR; extern "C" { PVR_ERROR GetEPGForChannel(ADDON_HANDLE handle, const PVR_CHANNEL& channel, time_t iStart, time_t iEnd) { for (const auto& epg : g_schedule.fetch(g_channels.getId(static_cast<int>(channel.iUniqueId)), iStart, iEnd)) { EPG_TAG tag = { .iUniqueBroadcastId = static_cast<unsigned int>(epg.id % 100000ul), .iUniqueChannelId = channel.iUniqueId, .strTitle = epg.name.c_str(), .startTime = epg.startAt, .endTime = epg.endAt, .strPlotOutline = epg.description.c_str(), .strPlot = epg.extended.c_str(), .strOriginalTitle = epg.name.c_str(), }; const auto genre = epgstation::getGenreCodeFromContentNibble(epg.genre1, epg.genre2); tag.iGenreType = genre.main; tag.iGenreSubType = genre.sub; PVR->TransferEpgEntry(handle, &tag); } return PVR_ERROR_NO_ERROR; } PVR_ERROR IsEPGTagRecordable(const EPG_TAG* tag, bool* bIsRecordable) { *bIsRecordable = true; return PVR_ERROR_NO_ERROR; } PVR_ERROR IsEPGTagPlayable(const EPG_TAG* tag, bool* bIsPlayable) { *bIsPlayable = true; return PVR_ERROR_NO_ERROR; } void* liveStreamHandle = nullptr; bool OpenLiveStream(const PVR_CHANNEL& channel) { char url[1024]; snprintf(url, sizeof(url) - 1, g_channels.liveStreamingPath.c_str(), g_channels.getId(static_cast<int>(channel.iUniqueId))); liveStreamHandle = XBMC->OpenFile(url, 0); return liveStreamHandle != nullptr; } void CloseLiveStream(void) { if (liveStreamHandle != nullptr) XBMC->CloseFile(liveStreamHandle); liveStreamHandle = nullptr; } int ReadLiveStream(unsigned char* pBuffer, unsigned int iBufferSize) { return XBMC->ReadFile(liveStreamHandle, pBuffer, iBufferSize); } bool IsRealTimeStream() { return true; } /* not implemented */ PVR_ERROR GetEPGTagStreamProperties(const EPG_TAG* tag, PVR_NAMED_VALUE* properties, unsigned int* iPropertiesCount) { return PVR_ERROR_NOT_IMPLEMENTED; } PVR_ERROR GetEPGTagEdl(const EPG_TAG* epgTag, PVR_EDL_ENTRY edl[], int* size) { return PVR_ERROR_NOT_IMPLEMENTED; } long long SeekLiveStream(long long iPosition, int iWhence) { return -1; } long long LengthLiveStream(void) { return -1; } }
2,726
C++
.cpp
74
32.756757
154
0.717424
Harekaze/pvr.epgstation
33
6
2
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,772
information.cpp
Harekaze_pvr_epgstation/src/pvr_client/information.cpp
/* * Copyright (C) 2015-2020 Yuki MIZUNO * https://github.com/Harekaze/pvr.epgstation/ * SPDX-License-Identifier: GPL-3.0-only */ #include "epgstation/docs.h" #include "kodi/libKODI_guilib.h" #include "kodi/libXBMC_addon.h" #include "kodi/libXBMC_pvr.h" #include <iostream> extern ADDON::CHelper_libXBMC_addon* XBMC; extern CHelper_libXBMC_pvr* PVR; char serverUrl[1024]; extern "C" { PVR_ERROR GetAddonCapabilities(PVR_ADDON_CAPABILITIES* pCapabilities) { pCapabilities->bSupportsEPG = true; pCapabilities->bSupportsTV = true; pCapabilities->bSupportsRadio = false; pCapabilities->bSupportsRecordings = true; pCapabilities->bSupportsRecordingsUndelete = false; pCapabilities->bSupportsTimers = true; pCapabilities->bSupportsChannelGroups = true; pCapabilities->bSupportsChannelScan = false; pCapabilities->bSupportsChannelSettings = false; pCapabilities->bHandlesInputStream = false; pCapabilities->bHandlesDemuxing = false; pCapabilities->bSupportsRecordingPlayCount = false; pCapabilities->bSupportsLastPlayedPosition = false; pCapabilities->bSupportsRecordingEdl = false; pCapabilities->bSupportsRecordingsRename = false; pCapabilities->bSupportsRecordingsLifetimeChange = false; pCapabilities->bSupportsDescrambleInfo = false; pCapabilities->iRecordingsLifetimesSize = 0; return PVR_ERROR_NO_ERROR; } const char* GetConnectionString(void) { if (XBMC->GetSetting("server_url", &serverUrl)) { return serverUrl; } return ""; } const char* GetBackendName(void) { return epgstation::Docs::getBackendName(); } const char* GetBackendVersion(void) { return epgstation::Docs::getBackendVersion(); } const char* GetBackendHostname(void) { return epgstation::Docs::getBackendHostname(); } /* not implemented */ PVR_ERROR GetDescrambleInfo(PVR_DESCRAMBLE_INFO* descrambleInfo) { return PVR_ERROR_NOT_IMPLEMENTED; } }
1,933
C++
.cpp
58
30.206897
102
0.774142
Harekaze/pvr.epgstation
33
6
2
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
1,541,773
timer.cpp
Harekaze_pvr_epgstation/src/pvr_client/timer.cpp
/* * Copyright (C) 2015-2020 Yuki MIZUNO * https://github.com/Harekaze/pvr.epgstation/ * SPDX-License-Identifier: GPL-3.0-only */ #include "epgstation/epgstation.h" #include "epgstation/genre.h" #include "epgstation/types.h" #include "kodi/libKODI_guilib.h" #include "kodi/libXBMC_addon.h" #include "kodi/libXBMC_pvr.h" #include <climits> #include <iostream> #if defined(_WIN32) || defined(_WIN64) #include <windows.h> #define sleep(sec) Sleep(sec) #else #include <unistd.h> #endif constexpr int CREATE_TIMER_MANUAL_RESERVED = 0x11; constexpr int CREATE_RULES_PATTERN_MATCHED = 0x12; constexpr unsigned int TIMER_MANUAL_RESERVED = 0x01; constexpr unsigned int TIMER_PATTERN_MATCHED = 0x02; #define MSG_TIMER_MANUAL_RESERVED 30900 #define MSG_TIMER_PATTERN_MATCHED 30901 #define MSG_RULES_PATTERN_MATCHED_CREATION 30902 extern ADDON::CHelper_libXBMC_addon* XBMC; extern CHelper_libXBMC_pvr* PVR; extern epgstation::Recorded g_recorded; extern epgstation::Schedule g_schedule; extern epgstation::Rule g_rule; extern epgstation::Reserve g_reserve; extern epgstation::Channels g_channels; struct tm* localtime_now() { time_t now; time(&now); #if defined(_WIN32) || defined(_WIN64) return localtime(&now); // NOLINT #else struct tm time; return localtime_r(&now, &time); #endif } uint8_t get_hour(time_t time) { #if defined(_WIN32) || defined(_WIN64) return localtime(&time)->tm_hour; // NOLINT #else struct tm t; return localtime_r(&time, &t)->tm_hour; #endif } extern "C" { int GetTimersAmount(void) { if (g_rule.refresh() && g_reserve.refresh()) { return g_rule.rules.size() + g_reserve.reserves.size(); } return -1; } PVR_ERROR GetTimers(ADDON_HANDLE handle) { if (g_rule.refresh() && g_reserve.refresh()) { for (const auto& rule : g_rule.rules) { PVR_TIMER timer = { .iClientIndex = static_cast<unsigned int>(rule.id), .iParentClientIndex = PVR_TIMER_NO_PARENT, .iClientChannelUid = rule.station == 0 ? PVR_TIMER_ANY_CHANNEL : g_channels.getId(rule.station), .startTime = 0, .endTime = 0, .bStartAnyTime = rule.timeRange == 0, .bEndAnyTime = rule.timeRange == 0, .state = rule.enable ? PVR_TIMER_STATE_SCHEDULED : PVR_TIMER_STATE_DISABLED, .iTimerType = CREATE_RULES_PATTERN_MATCHED, }; timer.iWeekdays = rule.week; timer.bFullTextEpgSearch = rule.description; strncpy(timer.strTitle, rule.keyword.c_str(), PVR_ADDON_NAME_STRING_LENGTH - 1); if (!timer.bStartAnyTime) { auto time = localtime_now(); time->tm_hour = rule.startTime; time->tm_min = 0; timer.startTime = mktime(time); timer.endTime = timer.startTime + rule.timeRange * 60 * 60; } strncpy(timer.strEpgSearchString, rule.keyword.c_str(), PVR_ADDON_NAME_STRING_LENGTH - 1); strncpy(timer.strSummary, rule.keyword.c_str(), PVR_ADDON_DESC_STRING_LENGTH - 1); strncpy(timer.strDirectory, rule.directory.c_str(), PVR_ADDON_DESC_STRING_LENGTH - 1); PVR->TransferTimerEntry(handle, &timer); } const auto time = localtime_now(); const auto now = mktime(time); for (const auto& p : g_reserve.reserves) { struct PVR_TIMER timer = { .iClientIndex = static_cast<unsigned int>(p.id), .iParentClientIndex = static_cast<unsigned int>(p.ruleId), .iClientChannelUid = g_channels.getId(p.channelId), .startTime = p.startAt, .endTime = p.endAt, .bStartAnyTime = false, .bEndAnyTime = false, .state = PVR_TIMER_STATE_NEW, .iTimerType = p.ruleId != 0 ? TIMER_PATTERN_MATCHED : TIMER_MANUAL_RESERVED, }; const auto genre = epgstation::getGenreCodeFromContentNibble(p.genre1, p.genre2); timer.iGenreType = genre.main; timer.iGenreSubType = genre.sub; timer.iEpgUid = static_cast<unsigned int>(p.eventId); strncpy(timer.strTitle, p.name.c_str(), PVR_ADDON_NAME_STRING_LENGTH - 1); strncpy(timer.strSummary, (p.extended + p.description).c_str(), PVR_ADDON_DESC_STRING_LENGTH - 1); strncpy(timer.strDirectory, std::to_string(p.id).c_str(), PVR_ADDON_URL_STRING_LENGTH - 1); // NOTE: Store original ID switch (p.state) { case epgstation::STATE_RESERVED: { if (now < timer.startTime) { timer.state = PVR_TIMER_STATE_SCHEDULED; } else if (now < timer.endTime) { timer.state = PVR_TIMER_STATE_RECORDING; } else { timer.state = PVR_TIMER_STATE_COMPLETED; } break; } case epgstation::STATE_CONFLICT: timer.state = PVR_TIMER_STATE_CONFLICT_NOK; break; case epgstation::STATE_SKIPPED: timer.state = PVR_TIMER_STATE_DISABLED; break; } PVR->TransferTimerEntry(handle, &timer); } return PVR_ERROR_NO_ERROR; } return PVR_ERROR_SERVER_ERROR; } PVR_ERROR UpdateTimer(const PVR_TIMER& timer) { switch (timer.iTimerType) { case CREATE_RULES_PATTERN_MATCHED: { const auto rule = std::find_if(g_rule.rules.begin(), g_rule.rules.end(), [timer](epgstation::rule r) { return r.id == timer.iClientIndex; }); if (rule == g_rule.rules.end()) { XBMC->Log(ADDON::LOG_ERROR, "Rule not found: #%d", timer.iClientIndex); return PVR_ERROR_REJECTED; } if (timer.state == (rule->enable ? PVR_TIMER_STATE_SCHEDULED : PVR_TIMER_STATE_DISABLED)) { // Timer state is not changed. Update rule auto startHour = get_hour(timer.startTime); auto endHour = get_hour(timer.endTime); if (g_rule.edit(timer.iClientIndex, timer.state != PVR_TIMER_STATE_DISABLED, timer.strEpgSearchString, timer.bFullTextEpgSearch, g_channels.getId(timer.iClientChannelUid), timer.iWeekdays, startHour, endHour, timer.bStartAnyTime || timer.bEndAnyTime, timer.strDirectory)) { goto complete; } return PVR_ERROR_SERVER_ERROR; } else { switch (timer.state) { case PVR_TIMER_STATE_SCHEDULED: case PVR_TIMER_STATE_DISABLED: { bool enable = timer.state == PVR_TIMER_STATE_SCHEDULED; if (g_rule.enable(timer.iClientIndex, enable)) { goto complete; } return PVR_ERROR_SERVER_ERROR; } default: XBMC->Log(ADDON::LOG_ERROR, "Unknown state change: #%d", timer.iClientIndex); return PVR_ERROR_NOT_IMPLEMENTED; } } } case TIMER_PATTERN_MATCHED: { switch (timer.state) { case PVR_TIMER_STATE_SCHEDULED: if (g_reserve.restore(timer.strDirectory)) { goto complete; } return PVR_ERROR_SERVER_ERROR; case PVR_TIMER_STATE_DISABLED: if (g_reserve.remove(timer.strDirectory)) { goto complete; } return PVR_ERROR_SERVER_ERROR; default: XBMC->Log(ADDON::LOG_ERROR, "Unknown state change: %s", timer.strDirectory); return PVR_ERROR_NOT_IMPLEMENTED; } } default: { XBMC->Log(ADDON::LOG_ERROR, "Unknown iTimerType: %d", timer.iTimerType); return PVR_ERROR_NOT_IMPLEMENTED; } } complete: sleep(1); PVR->TriggerTimerUpdate(); return PVR_ERROR_NO_ERROR; } PVR_ERROR AddTimer(const PVR_TIMER& timer) { switch (timer.iTimerType) { case CREATE_RULES_PATTERN_MATCHED: { auto startHour = get_hour(timer.startTime); auto endHour = get_hour(timer.endTime); if (g_rule.add(timer.state != PVR_TIMER_STATE_DISABLED, timer.strEpgSearchString, timer.bFullTextEpgSearch, g_channels.getId(timer.iClientChannelUid), timer.iWeekdays, startHour, endHour, timer.bStartAnyTime || timer.bEndAnyTime, timer.strDirectory)) { goto complete; } return PVR_ERROR_SERVER_ERROR; } case CREATE_TIMER_MANUAL_RESERVED: { auto programs = g_schedule.list[g_channels.getId(timer.iClientChannelUid)]; if (programs.empty()) { programs = g_schedule.fetch(g_channels.getId(timer.iClientChannelUid), timer.startTime, timer.endTime); } const auto program = std::find_if(programs.begin(), programs.end(), [timer](epgstation::program p) { return p.startAt == timer.startTime; }); if (program != programs.end()) { if (g_reserve.add(std::to_string(program->id))) { goto complete; } return PVR_ERROR_SERVER_ERROR; } } } XBMC->Log(ADDON::LOG_ERROR, "Failed to reserve new program: nothing matched"); return PVR_ERROR_FAILED; complete: sleep(3); PVR->TriggerTimerUpdate(); return PVR_ERROR_NO_ERROR; } PVR_ERROR DeleteTimer(const PVR_TIMER& timer, bool bForceDelete) { switch (timer.iTimerType) { case TIMER_MANUAL_RESERVED: { if (g_reserve.remove(timer.strDirectory)) { sleep(1); PVR->TriggerRecordingUpdate(); PVR->TriggerTimerUpdate(); return PVR_ERROR_NO_ERROR; } return PVR_ERROR_SERVER_ERROR; } case CREATE_RULES_PATTERN_MATCHED: { if (g_rule.remove(timer.iClientIndex)) { sleep(1); PVR->TriggerRecordingUpdate(); PVR->TriggerTimerUpdate(); return PVR_ERROR_NO_ERROR; } return PVR_ERROR_SERVER_ERROR; } default: { XBMC->Log(ADDON::LOG_ERROR, "Unknown timer type for deletion request: %d", timer.iTimerType); return PVR_ERROR_NOT_IMPLEMENTED; } } } PVR_ERROR GetTimerTypes(PVR_TIMER_TYPE types[], int* size) { std::vector<PVR_TIMER_TYPE> tt = { { .iId = CREATE_RULES_PATTERN_MATCHED, .iAttributes = PVR_TIMER_TYPE_SUPPORTS_ENABLE_DISABLE | PVR_TIMER_TYPE_SUPPORTS_TITLE_EPG_MATCH | PVR_TIMER_TYPE_SUPPORTS_FULLTEXT_EPG_MATCH | PVR_TIMER_TYPE_SUPPORTS_CHANNELS | PVR_TIMER_TYPE_SUPPORTS_ANY_CHANNEL | PVR_TIMER_TYPE_SUPPORTS_START_TIME | PVR_TIMER_TYPE_SUPPORTS_START_ANYTIME | PVR_TIMER_TYPE_SUPPORTS_END_TIME | PVR_TIMER_TYPE_SUPPORTS_END_ANYTIME | PVR_TIMER_TYPE_SUPPORTS_WEEKDAYS | PVR_TIMER_TYPE_IS_REPEATING | PVR_TIMER_TYPE_SUPPORTS_RECORDING_FOLDERS, }, { .iId = CREATE_TIMER_MANUAL_RESERVED, .iAttributes = PVR_TIMER_TYPE_REQUIRES_EPG_TAG_ON_CREATE, }, { .iId = TIMER_MANUAL_RESERVED, .iAttributes = PVR_TIMER_TYPE_FORBIDS_NEW_INSTANCES | PVR_TIMER_TYPE_IS_READONLY | PVR_TIMER_TYPE_IS_MANUAL | PVR_TIMER_TYPE_SUPPORTS_START_TIME | PVR_TIMER_TYPE_SUPPORTS_END_TIME | PVR_TIMER_TYPE_SUPPORTS_READONLY_DELETE, }, { .iId = TIMER_PATTERN_MATCHED, .iAttributes = PVR_TIMER_TYPE_FORBIDS_NEW_INSTANCES | PVR_TIMER_TYPE_IS_READONLY | PVR_TIMER_TYPE_SUPPORTS_ENABLE_DISABLE, }, }; strncpy(std::find_if(tt.begin(), tt.end(), [](PVR_TIMER_TYPE t) { return t.iId == CREATE_RULES_PATTERN_MATCHED; })->strDescription, XBMC->GetLocalizedString(MSG_RULES_PATTERN_MATCHED_CREATION), PVR_ADDON_TIMERTYPE_STRING_LENGTH - 1); strncpy(std::find_if(tt.begin(), tt.end(), [](PVR_TIMER_TYPE t) { return t.iId == TIMER_MANUAL_RESERVED; })->strDescription, XBMC->GetLocalizedString(MSG_TIMER_MANUAL_RESERVED), PVR_ADDON_TIMERTYPE_STRING_LENGTH - 1); strncpy(std::find_if(tt.begin(), tt.end(), [](PVR_TIMER_TYPE t) { return t.iId == TIMER_PATTERN_MATCHED; })->strDescription, XBMC->GetLocalizedString(MSG_TIMER_PATTERN_MATCHED), PVR_ADDON_TIMERTYPE_STRING_LENGTH - 1); std::copy(tt.begin(), tt.end(), types); *size = tt.size(); return PVR_ERROR_NO_ERROR; } /* not implemented */ bool IsTimeshifting() { return false; } }
12,573
C++
.cpp
303
32.343234
135
0.612337
Harekaze/pvr.epgstation
33
6
2
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,774
recording.cpp
Harekaze_pvr_epgstation/src/pvr_client/recording.cpp
/* * Copyright (C) 2015-2020 Yuki MIZUNO * https://github.com/Harekaze/pvr.epgstation/ * SPDX-License-Identifier: GPL-3.0-only */ #include "epgstation/epgstation.h" #include "epgstation/genre.h" #include "kodi/libKODI_guilib.h" #include "kodi/libXBMC_addon.h" #include "kodi/libXBMC_pvr.h" #include <algorithm> #include <climits> #include <iostream> #if defined(_WIN32) || defined(_WIN64) #include <windows.h> #define sleep(sec) Sleep(sec) #else #include <unistd.h> #endif extern epgstation::Recorded g_recorded; extern epgstation::Channels g_channels; extern ADDON::CHelper_libXBMC_addon* XBMC; extern CHelper_libXBMC_pvr* PVR; extern CHelper_libKODI_guilib* GUI; extern "C" { int GetRecordingsAmount(bool deleted) { return g_recorded.programs.size(); } PVR_ERROR GetRecordings(ADDON_HANDLE handle, bool deleted) { if (g_recorded.refresh()) { for (const auto& r : g_recorded.programs) { const auto genre = epgstation::getGenreCodeFromContentNibble(r.genre1, r.genre2); PVR_RECORDING rec = {}; rec.recordingTime = r.startAt; rec.iDuration = static_cast<int>(r.endAt - r.startAt); rec.iGenreType = genre.main; rec.iGenreSubType = genre.sub; rec.iEpgEventId = static_cast<unsigned int>(r.programId % 100000); rec.iChannelUid = g_channels.getId(r.channelId); rec.channelType = PVR_RECORDING_CHANNEL_TYPE_TV; strncpy(rec.strRecordingId, std::to_string(r.id).c_str(), PVR_ADDON_NAME_STRING_LENGTH - 1); strncpy(rec.strTitle, r.name.c_str(), PVR_ADDON_NAME_STRING_LENGTH - 1); strncpy(rec.strPlotOutline, r.description.c_str(), PVR_ADDON_DESC_STRING_LENGTH - 1); strncpy(rec.strPlot, r.extended.c_str(), PVR_ADDON_DESC_STRING_LENGTH - 1); if (r.hasThumbnail) { snprintf(rec.strThumbnailPath, PVR_ADDON_URL_STRING_LENGTH - 1, g_recorded.recordedThumbnailPath.c_str(), rec.strRecordingId); } PVR->TransferRecordingEntry(handle, &rec); } return PVR_ERROR_NO_ERROR; } return PVR_ERROR_SERVER_ERROR; } PVR_ERROR GetRecordingStreamProperties(const PVR_RECORDING* recording, PVR_NAMED_VALUE* properties, unsigned int* iPropertiesCount) { const auto rec = std::find_if(g_recorded.programs.begin(), g_recorded.programs.end(), [recording](epgstation::program p) { return p.id == std::stoull(recording->strRecordingId); }); if (rec == g_recorded.programs.end()) { XBMC->Log(ADDON::LOG_ERROR, "Recording not found: #%s", recording->strRecordingId); return PVR_ERROR_FAILED; } strncpy(properties[0].strName, PVR_STREAM_PROPERTY_STREAMURL, sizeof(properties[0].strName) - 1); int prefer_encoded; XBMC->GetSetting("prefer_encoded", &prefer_encoded); const auto ignoreOriginalPlayback = !rec->encoded.empty() && prefer_encoded; if (!rec->original || ignoreOriginalPlayback) { auto id = rec->encoded[0].first; if (rec->encoded.size() > 1) { std::vector<const char*> entries; std::transform(rec->encoded.begin(), rec->encoded.end(), std::back_inserter(entries), [](std::pair<uint64_t, std::string>& s) { return s.second.c_str(); }); entries.push_back(nullptr); const auto selected = GUI->Dialog_Select("Select media", entries.data(), rec->encoded.size()); if (selected < 0) { return PVR_ERROR_NOT_IMPLEMENTED; } id = rec->encoded[selected].first; } const auto param = "?encodedId=" + std::to_string(id); snprintf(properties[0].strValue, sizeof(properties[0].strValue) - 1, (g_recorded.recordedStreamingPath + param).c_str(), recording->strRecordingId); } else { snprintf(properties[0].strValue, sizeof(properties[0].strValue) - 1, g_recorded.recordedStreamingPath.c_str(), recording->strRecordingId); } *iPropertiesCount = 1; return PVR_ERROR_NO_ERROR; } PVR_ERROR DeleteRecording(const PVR_RECORDING& recording) { if (g_recorded.remove(recording.strRecordingId)) { sleep(1); PVR->TriggerRecordingUpdate(); return PVR_ERROR_NO_ERROR; } return PVR_ERROR_SERVER_ERROR; } PVR_ERROR GetDriveSpace(long long* iTotal, long long* iUsed) { return epgstation::Storage::getStorageInfo(iUsed, iTotal); } /* not implemented */ PVR_ERROR UndeleteRecording(const PVR_RECORDING& recording) { return PVR_ERROR_NOT_IMPLEMENTED; } PVR_ERROR DeleteAllRecordingsFromTrash(void) { return PVR_ERROR_NOT_IMPLEMENTED; } PVR_ERROR RenameRecording(const PVR_RECORDING& recording) { return PVR_ERROR_NOT_IMPLEMENTED; } PVR_ERROR SetRecordingLifetime(const PVR_RECORDING* recording) { return PVR_ERROR_NOT_IMPLEMENTED; } PVR_ERROR SetRecordingPlayCount(const PVR_RECORDING& recording, int count) { return PVR_ERROR_NOT_IMPLEMENTED; } PVR_ERROR SetRecordingLastPlayedPosition(const PVR_RECORDING& recording, int lastplayedposition) { return PVR_ERROR_NOT_IMPLEMENTED; } int GetRecordingLastPlayedPosition(const PVR_RECORDING& recording) { return -1; } PVR_ERROR GetRecordingEdl(const PVR_RECORDING&, PVR_EDL_ENTRY[], int*) { return PVR_ERROR_NOT_IMPLEMENTED; } bool OpenRecordedStream(const PVR_RECORDING& recording) { return false; } void CloseRecordedStream(void) {} int ReadRecordedStream(unsigned char* pBuffer, unsigned int iBufferSize) { return 0; } long long SeekRecordedStream(long long iPosition, int iWhence) { return 0; } long long LengthRecordedStream(void) { return 0; } }
5,594
C++
.cpp
118
41.652542
156
0.69738
Harekaze/pvr.epgstation
33
6
2
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,775
channel.cpp
Harekaze_pvr_epgstation/src/pvr_client/channel.cpp
/* * Copyright (C) 2015-2020 Yuki MIZUNO * https://github.com/Harekaze/pvr.epgstation/ * SPDX-License-Identifier: GPL-3.0-only */ #include "epgstation/epgstation.h" #include "kodi/libKODI_guilib.h" #include "kodi/libXBMC_addon.h" #include "kodi/libXBMC_pvr.h" #include <iostream> #include <set> extern epgstation::Channels g_channels; extern ADDON::CHelper_libXBMC_addon* XBMC; extern CHelper_libXBMC_pvr* PVR; extern "C" { int GetChannelsAmount(void) { if (!g_channels.refresh()) { return PVR_ERROR_SERVER_ERROR; } return g_channels.channels.size(); } PVR_ERROR GetChannels(ADDON_HANDLE handle, bool bRadio) { if (bRadio) { return PVR_ERROR_NO_ERROR; } if (!g_channels.refresh()) { return PVR_ERROR_SERVER_ERROR; } std::vector<std::string> transferred; for (const auto& c : g_channels.channels) { PVR_CHANNEL ch = { .iUniqueId = static_cast<unsigned int>(g_channels.getId(c.id)), .bIsRadio = false, .iChannelNumber = c.remoteControlKeyId, .iSubChannelNumber = c.serviceId, }; if (std::find(transferred.begin(), transferred.end(), c.channelStr) != transferred.end()) { XBMC->Log(ADDON::LOG_DEBUG, "Hide \"%s\" because main channel of %s is transferred", c.name.c_str(), c.channelStr.c_str()); ch.bIsHidden = true; } strncpy(ch.strChannelName, c.name.c_str(), PVR_ADDON_NAME_STRING_LENGTH - 1); if (c.hasLogoData) { snprintf(ch.strIconPath, PVR_ADDON_URL_STRING_LENGTH - 1, g_channels.channelLogoPath.c_str(), c.id); } PVR->TransferChannelEntry(handle, &ch); transferred.push_back(c.channelStr); } return PVR_ERROR_NO_ERROR; } int GetChannelGroupsAmount(void) { std::set<std::string> list; for (const auto& channel : g_channels.channels) { list.insert(channel.channelType); } return list.size(); } PVR_ERROR GetChannelGroups(ADDON_HANDLE handle, bool bRadio) { std::set<std::string> list; for (const auto& channel : g_channels.channels) { list.insert(channel.channelType); } for (const auto& channelType : list) { PVR_CHANNEL_GROUP chGroup = {}; strncpy(chGroup.strGroupName, channelType.c_str(), PVR_ADDON_NAME_STRING_LENGTH - 1); PVR->TransferChannelGroup(handle, &chGroup); } return PVR_ERROR_NO_ERROR; } PVR_ERROR GetChannelGroupMembers(ADDON_HANDLE handle, const PVR_CHANNEL_GROUP& group) { for (const auto& c : g_channels.channels) { if (c.channelType != group.strGroupName) { continue; } PVR_CHANNEL_GROUP_MEMBER chMem = {}; chMem.iChannelUniqueId = static_cast<unsigned int>(g_channels.getId(c.id)); chMem.iChannelNumber = c.remoteControlKeyId; strncpy(chMem.strGroupName, group.strGroupName, PVR_ADDON_NAME_STRING_LENGTH - 1); PVR->TransferChannelGroupMember(handle, &chMem); } return PVR_ERROR_NO_ERROR; } /* not implemented */ PVR_ERROR OpenDialogChannelScan(void) { return PVR_ERROR_NOT_IMPLEMENTED; } PVR_ERROR DeleteChannel(const PVR_CHANNEL& channel) { return PVR_ERROR_NOT_IMPLEMENTED; } PVR_ERROR RenameChannel(const PVR_CHANNEL& channel) { return PVR_ERROR_NOT_IMPLEMENTED; } PVR_ERROR OpenDialogChannelSettings(const PVR_CHANNEL& channel) { return PVR_ERROR_NOT_IMPLEMENTED; } PVR_ERROR OpenDialogChannelAdd(const PVR_CHANNEL& channel) { return PVR_ERROR_NOT_IMPLEMENTED; } PVR_ERROR SetEPGTimeFrame(int iDays) { return PVR_ERROR_NOT_IMPLEMENTED; } PVR_ERROR GetChannelStreamProperties(const PVR_CHANNEL* channel, PVR_NAMED_VALUE* properties, unsigned int* iPropertiesCount) { return PVR_ERROR_NOT_IMPLEMENTED; } }
3,742
C++
.cpp
95
34.084211
163
0.690844
Harekaze/pvr.epgstation
33
6
2
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,776
initialize.cpp
Harekaze_pvr_epgstation/src/pvr_client/initialize.cpp
/* * Copyright (C) 2015-2020 Yuki MIZUNO * https://github.com/Harekaze/pvr.epgstation/ * SPDX-License-Identifier: GPL-3.0-only */ #include "epgstation/api.h" #include "epgstation/epgstation.h" #include "kodi/libKODI_guilib.h" #include "kodi/libXBMC_addon.h" #include "kodi/libXBMC_pvr.h" #include "kodi/xbmc_pvr_dll.h" #include <climits> #include <cstdio> #include <iostream> #define MENUHOOK_FORCE_REFRESH_RECORDING 0x01 #define MENUHOOK_FORCE_REFRESH_TIMER 0x02 #define MENUHOOK_FORCE_EXECUTE_SCHEDULER 0x04 #define MSG_FORCE_REFRESH_RECORDING 30800 #define MSG_FORCE_REFRESH_TIMER 30801 #define MSG_FORCE_EXECUTE_SCHEDULER 30802 epgstation::Channels g_channels; epgstation::Schedule g_schedule; epgstation::Recorded g_recorded; epgstation::Rule g_rule; epgstation::Reserve g_reserve; ADDON::CHelper_libXBMC_addon* XBMC = nullptr; CHelper_libXBMC_pvr* PVR = nullptr; CHelper_libKODI_guilib* GUI = nullptr; time_t lastStartTime; ADDON_STATUS currentStatus = ADDON_STATUS_UNKNOWN; extern "C" { ADDON_STATUS ADDON_Create(void* callbacks, void* props) { if (!callbacks || !props) { return ADDON_STATUS_UNKNOWN; } XBMC = new ADDON::CHelper_libXBMC_addon; PVR = new CHelper_libXBMC_pvr; GUI = new CHelper_libKODI_guilib; if ( !XBMC->RegisterMe(callbacks) || !PVR->RegisterMe(callbacks) || !GUI->RegisterMe(callbacks)) { delete PVR; delete XBMC; delete GUI; PVR = nullptr; XBMC = nullptr; GUI = nullptr; return ADDON_STATUS_PERMANENT_FAILURE; } time(&lastStartTime); const char* strUserPath = static_cast<PVR_PROPERTIES*>(props)->strUserPath; if (!XBMC->DirectoryExists(strUserPath)) { XBMC->CreateDirectory(strUserPath); } char serverUrl[1024]; if (XBMC->GetSetting("server_url", &serverUrl)) { epgstation::api::baseURL = serverUrl; constexpr char httpPrefix[] = "http://"; constexpr char httpsPrefix[] = "https://"; if (epgstation::api::baseURL.rfind(httpPrefix, 0) != 0 && epgstation::api::baseURL.rfind(httpsPrefix, 0) != 0) { if (currentStatus == ADDON_STATUS_UNKNOWN) { XBMC->QueueNotification(ADDON::QUEUE_WARNING, XBMC->GetLocalizedString(30600)); currentStatus = ADDON_STATUS_NEED_SETTINGS; } return currentStatus; } if (*(epgstation::api::baseURL.end() - 1) != '/') { epgstation::api::baseURL += "/"; } epgstation::api::baseURL += "api/"; } g_channels.liveStreamingPath = epgstation::api::baseURL + "streams/live/%llu/mpegts"; g_channels.channelLogoPath = epgstation::api::baseURL + "channels/%llu/logo"; g_recorded.recordedStreamingPath = epgstation::api::baseURL + "recorded/%s/file"; g_recorded.recordedThumbnailPath = epgstation::api::baseURL + "recorded/%s/thumbnail"; unsigned int mode; XBMC->GetSetting("live_transcode", &mode); std::string transcodeParams = "?mode=" + std::to_string(mode); XBMC->Log(ADDON::LOG_NOTICE, "Transcoding parameter: %s", transcodeParams.c_str()); g_channels.liveStreamingPath += transcodeParams; PVR_MENUHOOK menuHookRec = { .iHookId = MENUHOOK_FORCE_REFRESH_RECORDING, .iLocalizedStringId = MSG_FORCE_REFRESH_RECORDING, .category = PVR_MENUHOOK_RECORDING, }; PVR->AddMenuHook(&menuHookRec); PVR_MENUHOOK menuHookTimer = { .iHookId = MENUHOOK_FORCE_REFRESH_TIMER, .iLocalizedStringId = MSG_FORCE_REFRESH_TIMER, .category = PVR_MENUHOOK_TIMER, }; PVR->AddMenuHook(&menuHookTimer); PVR_MENUHOOK menuHookScheduler = { .iHookId = MENUHOOK_FORCE_EXECUTE_SCHEDULER, .iLocalizedStringId = MSG_FORCE_EXECUTE_SCHEDULER, .category = PVR_MENUHOOK_EPG, }; PVR->AddMenuHook(&menuHookScheduler); currentStatus = ADDON_STATUS_OK; return currentStatus; } ADDON_STATUS ADDON_GetStatus(void) { return currentStatus; } void ADDON_Destroy(void) { currentStatus = ADDON_STATUS_UNKNOWN; } // Settings configuration ADDON_STATUS ADDON_SetSetting(const char* settingName, const void* settingValue) { time_t now; time(&now); if (now - 2 < lastStartTime) { return currentStatus; } if (currentStatus == ADDON_STATUS_OK) { return ADDON_STATUS_NEED_RESTART; } return ADDON_STATUS_PERMANENT_FAILURE; } PVR_ERROR CallMenuHook(const PVR_MENUHOOK& menuhook, const PVR_MENUHOOK_DATA& item) { switch (menuhook.iHookId) { case MENUHOOK_FORCE_REFRESH_RECORDING: { PVR->TriggerRecordingUpdate(); return PVR_ERROR_NO_ERROR; } case MENUHOOK_FORCE_REFRESH_TIMER: { PVR->TriggerTimerUpdate(); return PVR_ERROR_NO_ERROR; } case MENUHOOK_FORCE_EXECUTE_SCHEDULER: { if (g_schedule.update()) { PVR->TriggerChannelUpdate(); return PVR_ERROR_NO_ERROR; } return PVR_ERROR_SERVER_ERROR; } } return PVR_ERROR_FAILED; } void OnSystemWake() { PVR->TriggerRecordingUpdate(); PVR->TriggerTimerUpdate(); PVR->TriggerChannelUpdate(); } void OnPowerSavingDeactivated() { PVR->TriggerRecordingUpdate(); PVR->TriggerTimerUpdate(); PVR->TriggerChannelUpdate(); } /* not implemented */ void OnSystemSleep() {} void OnPowerSavingActivated() {} PVR_ERROR GetStreamTimes(PVR_STREAM_TIMES* times) { return PVR_ERROR_NOT_IMPLEMENTED; } }
5,485
C++
.cpp
162
28.703704
120
0.687004
Harekaze/pvr.epgstation
33
6
2
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,778
recorded.cpp
Harekaze_pvr_epgstation/src/epgstation/recorded.cpp
/* * Copyright (C) 2015-2020 Yuki MIZUNO * https://github.com/Harekaze/pvr.epgstation/ * SPDX-License-Identifier: GPL-3.0-only */ #include "epgstation/recorded.h" #include "epgstation/api.h" #include "epgstation/schedule.h" #include "epgstation/types.h" #include "kodi/libXBMC_addon.h" #include "json/json.hpp" #include <algorithm> #include <string> extern ADDON::CHelper_libXBMC_addon* XBMC; namespace epgstation { bool Recorded::refresh() { nlohmann::json response; programs.clear(); if (api::getRecorded(response) == api::REQUEST_FAILED) { return false; } std::copy(response["recorded"].begin(), response["recorded"].end(), std::back_inserter(programs)); XBMC->Log(ADDON::LOG_NOTICE, "Updated recorded program: ammount = %d", programs.size()); return true; } bool Recorded::remove(const std::string id) { const auto success = api::deleteRecordedProgram(id) != api::REQUEST_FAILED; XBMC->Log(success ? ADDON::LOG_NOTICE : ADDON::LOG_ERROR, "Recording deletion: #%s", id.c_str()); return success; } } // namespace epgstation
1,093
C++
.cpp
34
29.176471
102
0.711027
Harekaze/pvr.epgstation
33
6
2
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,779
reserves.cpp
Harekaze_pvr_epgstation/src/epgstation/reserves.cpp
/* * Copyright (C) 2015-2020 Yuki MIZUNO * https://github.com/Harekaze/pvr.epgstation/ * SPDX-License-Identifier: GPL-3.0-only */ #include "epgstation/reserves.h" #include "epgstation/api.h" #include "epgstation/recorded.h" #include "epgstation/schedule.h" #include "epgstation/types.h" #include "kodi/libXBMC_addon.h" #include "json/json.hpp" #include <algorithm> #include <map> #include <string> extern ADDON::CHelper_libXBMC_addon* XBMC; namespace epgstation { bool Reserve::refresh() { nlohmann::json response; std::map<ReservedState, int (*)(nlohmann::json & response)> requests = { { STATE_RESERVED, api::getReserves }, { STATE_CONFLICT, api::getReservesConflicts }, { STATE_SKIPPED, api::getReservesSkips }, }; reserves.clear(); for (const auto& request : requests) { if (request.second(response) == api::REQUEST_FAILED) { return false; } std::transform(response["reserves"].begin(), response["reserves"].end(), std::back_inserter(reserves), [request](const nlohmann::json& r) { auto p = r["program"].get<program>(); p.ruleId = r.contains("ruleId") && r["ruleId"].is_number() ? r["ruleId"].get<int16_t>() : 0; p.state = request.first; return p; }); } XBMC->Log(ADDON::LOG_NOTICE, "Updated conflicted program: ammount = %d", response["reserves"].size()); return true; } bool Reserve::add(const std::string id) { const auto success = api::postReserves(id) != api::REQUEST_FAILED; XBMC->Log(success ? ADDON::LOG_NOTICE : ADDON::LOG_ERROR, "Program reservation: #%s", id.c_str()); return success; } bool Reserve::remove(const std::string id) { const auto success = api::deleteReserves(id) != api::REQUEST_FAILED; XBMC->Log(success ? ADDON::LOG_NOTICE : ADDON::LOG_ERROR, "Program deletion: #%s", id.c_str()); return success; } bool Reserve::restore(const std::string id) { const auto success = api::deleteReservesSkip(id) != api::REQUEST_FAILED; XBMC->Log(success ? ADDON::LOG_NOTICE : ADDON::LOG_ERROR, "Program restoration: #%s", id.c_str()); return success; } } // namespace epgstation
2,214
C++
.cpp
62
31.129032
147
0.65873
Harekaze/pvr.epgstation
33
6
2
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,780
channels.cpp
Harekaze_pvr_epgstation/src/epgstation/channels.cpp
/* * Copyright (C) 2015-2020 Yuki MIZUNO * https://github.com/Harekaze/pvr.epgstation/ * SPDX-License-Identifier: GPL-3.0-only */ #include "epgstation/channels.h" #include "epgstation/api.h" #include "epgstation/types.h" #include "kodi/libXBMC_addon.h" #include "json/json.hpp" #include <algorithm> #include <string> #include <vector> extern ADDON::CHelper_libXBMC_addon* XBMC; namespace epgstation { bool Channels::refresh() { nlohmann::json response; channels.clear(); if (api::getChannels(response) == api::REQUEST_FAILED) { return false; } std::copy_if(response.begin(), response.end(), std::back_inserter(channels), [](epgstation::channel c) { return c.type != 0xC0; // filter 1-seg channel }); int id = 1; for (auto ch = channels.begin(); ch != channels.end(); ++ch, ++id) { ch->internalId = id; } XBMC->Log(ADDON::LOG_NOTICE, "Updated channels: channel ammount = %d", channels.size()); return true; } int Channels::getId(uint64_t realId) { return std::find_if(channels.begin(), channels.end(), [realId](epgstation::channel ch) { return ch.id == realId; })->internalId; } uint64_t Channels::getId(int internalId) { return std::find_if(channels.begin(), channels.end(), [internalId](epgstation::channel ch) { return ch.internalId == internalId; })->id; } } // namespace epgstation
1,399
C++
.cpp
45
27.577778
108
0.67658
Harekaze/pvr.epgstation
33
6
2
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,781
schedule.cpp
Harekaze_pvr_epgstation/src/epgstation/schedule.cpp
/* * Copyright (C) 2015-2020 Yuki MIZUNO * https://github.com/Harekaze/pvr.epgstation/ * SPDX-License-Identifier: GPL-3.0-only */ #include "epgstation/schedule.h" #include "epgstation/api.h" #include "epgstation/types.h" #include "kodi/libXBMC_addon.h" #include "json/json.hpp" #include <algorithm> #include <string> #include <time.h> #include <vector> extern ADDON::CHelper_libXBMC_addon* XBMC; namespace epgstation { std::vector<program> Schedule::fetch(uint32_t channelId, time_t start, time_t end) { nlohmann::json response; list[channelId] = std::vector<program>(); #if defined(_WIN32) || defined(_WIN64) const auto t = localtime(&start); // NOLINT #else auto t = new struct tm; localtime_r(&start, t); #endif char time[10] = { 0 }; strftime(time, sizeof(time) - 1, "%y%m%d%H", t); const auto days = static_cast<uint16_t>(std::ceil(difftime(end, start) / 86400)); #if !defined(_WIN32) && !defined(_WIN64) delete t; #endif if (api::getSchedule(std::to_string(channelId), time, days, response) == api::REQUEST_FAILED) { return list[channelId]; } for (const auto& o : response) { std::copy(o["programs"].begin(), o["programs"].end(), std::back_inserter(list[channelId])); } return list[channelId]; } bool Schedule::update() { const auto success = api::putScheduleUpdate() != epgstation::api::REQUEST_FAILED; XBMC->Log(success ? ADDON::LOG_NOTICE : ADDON::LOG_ERROR, "Schedule update"); return success; } } // namespace epgstation
1,528
C++
.cpp
47
29.468085
99
0.686354
Harekaze/pvr.epgstation
33
6
2
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,782
rules.cpp
Harekaze_pvr_epgstation/src/epgstation/rules.cpp
/* * Copyright (C) 2015-2020 Yuki MIZUNO * https://github.com/Harekaze/pvr.epgstation/ * SPDX-License-Identifier: GPL-3.0-only */ #include "epgstation/rules.h" #include "epgstation/api.h" #include "epgstation/recorded.h" #include "epgstation/reserves.h" #include "epgstation/schedule.h" #include "epgstation/types.h" #include "kodi/libXBMC_addon.h" #include "json/json.hpp" #include <algorithm> #include <string> extern ADDON::CHelper_libXBMC_addon* XBMC; namespace epgstation { bool Rule::refresh() { nlohmann::json response; rules.clear(); if (api::getRules(response) == api::REQUEST_FAILED) { return false; } std::copy(response["rules"].begin(), response["rules"].end(), std::back_inserter(rules)); XBMC->Log(ADDON::LOG_NOTICE, "Updated rules: ammount = %d", rules.size()); return true; } bool Rule::add(bool enabled, const std::string searchText, bool fullText, uint64_t channelId, unsigned int weekdays, unsigned int startHour, unsigned int endHour, bool anytime, const std::string directory) { const auto success = api::postRules(enabled, searchText, fullText, channelId, weekdays, startHour, endHour, anytime, directory) != api::REQUEST_FAILED; XBMC->Log(success ? ADDON::LOG_NOTICE : ADDON::LOG_ERROR, "Rule creation: \"%s\"", searchText.c_str()); return success; } bool Rule::edit(int id, bool enabled, const std::string searchText, bool fullText, uint64_t channelId, unsigned int weekdays, unsigned int startHour, unsigned int endHour, bool anytime, const std::string directory) { const auto success = api::putRule(id, enabled, searchText, fullText, channelId, weekdays, startHour, endHour, anytime, directory) != api::REQUEST_FAILED; XBMC->Log(success ? ADDON::LOG_NOTICE : ADDON::LOG_ERROR, "Rule update: #%d", id); return success; } bool Rule::enable(int id, bool enabled) { const auto success = api::putRuleAction(id, enabled) != api::REQUEST_FAILED; XBMC->Log(success ? ADDON::LOG_NOTICE : ADDON::LOG_ERROR, "Rule state change: %s #%d", enabled ? "enable" : "disable", id); return success; } bool Rule::remove(int id) { const auto success = api::deleteRule(id) != api::REQUEST_FAILED; XBMC->Log(success ? ADDON::LOG_NOTICE : ADDON::LOG_ERROR, "Rule delete: #%d", id); return success; } } // namespace epgstation
2,349
C++
.cpp
56
38.767857
214
0.713097
Harekaze/pvr.epgstation
33
6
2
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,783
api.cpp
Harekaze_pvr_epgstation/src/epgstation/api.cpp
/* * Copyright (C) 2015-2020 Yuki MIZUNO * https://github.com/Harekaze/pvr.epgstation/ * SPDX-License-Identifier: GPL-3.0-only */ #include "epgstation/api.h" #include "../base64/base64.h" #include "kodi/libXBMC_addon.h" #include "kodi/libXBMC_pvr.h" #include "json/json.hpp" #include <string> #if defined(_WIN32) || defined(_WIN64) #include <windows.h> #define sleep(sec) Sleep(sec) #else #include <unistd.h> #endif extern ADDON::CHelper_libXBMC_addon* XBMC; extern CHelper_libXBMC_pvr* PVR; namespace epgstation { namespace api { const int REQUEST_FAILED = -1; std::string baseURL = ""; int request(const std::string method, const std::string path, nlohmann::json* response = nullptr, nlohmann::json body = nullptr) { const auto url = baseURL + path; XBMC->Log(ADDON::LOG_DEBUG, "Request URL: %s", url.c_str()); XBMC->Log(ADDON::LOG_DEBUG, "Request Method: %s", method.c_str()); std::string text; void* handle = XBMC->CURLCreate(url.c_str()); if (handle == nullptr) { XBMC->Log(ADDON::LOG_ERROR, "Failed to create URL: %s", url.c_str()); return REQUEST_FAILED; } if (method != "GET") { if (!XBMC->CURLAddOption(handle, XFILE::CURLOPTIONTYPE::CURL_OPTION_PROTOCOL, "customrequest", method.c_str())) { XBMC->Log(ADDON::LOG_ERROR, "Failed to set %s method to %s", method.c_str(), url.c_str()); XBMC->CloseFile(handle); return REQUEST_FAILED; } } if (body != nullptr) { XBMC->Log(ADDON::LOG_DEBUG, "Setting request header"); if (!XBMC->CURLAddOption(handle, XFILE::CURLOPTIONTYPE::CURL_OPTION_HEADER, "Content-Type", "application/json")) { XBMC->Log(ADDON::LOG_ERROR, "Failed to set content-type to %s", url.c_str()); XBMC->CloseFile(handle); return REQUEST_FAILED; } XBMC->Log(ADDON::LOG_DEBUG, "Setting request body"); const std::string data = base64_encode(body.dump()); if (!XBMC->CURLAddOption(handle, XFILE::CURLOPTIONTYPE::CURL_OPTION_PROTOCOL, "postdata", data.c_str())) { XBMC->Log(ADDON::LOG_ERROR, "Failed to set post data to %s", url.c_str()); XBMC->CloseFile(handle); return REQUEST_FAILED; } } XBMC->Log(ADDON::LOG_DEBUG, "Open url for requesting"); constexpr uint8_t retry_limit = 3; uint8_t retry = 0; do { if (XBMC->CURLOpen(handle, XFILE::READ_NO_CACHE)) { break; } XBMC->Log(ADDON::LOG_ERROR, "Failed to open URL: %s (retry %d)", url.c_str(), retry); if (++retry >= retry_limit) { XBMC->CloseFile(handle); return REQUEST_FAILED; } sleep(3); } while (1); if (response != nullptr) { XBMC->Log(ADDON::LOG_DEBUG, "Read response body"); constexpr uint16_t buffer_size = 4096; auto buffer = new char[buffer_size]; while (auto bytesRead = XBMC->ReadFile(handle, buffer, buffer_size)) { text.append(buffer, bytesRead); } delete[] buffer; } XBMC->CloseFile(handle); if (response != nullptr && !text.empty()) { try { *response = nlohmann::json::parse(text); } catch (nlohmann::json::parse_error err) { XBMC->Log(ADDON::LOG_ERROR, "Failed to parse JSON string: %s", err.what()); return REQUEST_FAILED; } } XBMC->Log(ADDON::LOG_DEBUG, "Complete API request for %s", url.c_str()); return 0; } // GET /api/channels int getChannels(nlohmann::json& response) { const auto apiPath = "channels"; return request("GET", apiPath, &response); } // GET /api/schedule?type=:type int getScheduleAll(const std::string type, nlohmann::json& response) { const auto apiPath = "schedule?type=" + type; return request("GET", apiPath, &response); } // GET /api/schedule/:id?time=:time&days=:days int getSchedule(const std::string id, const char* time, const uint16_t days, nlohmann::json& response) { const auto apiPath = "schedule/" + id + "?time=" + time + "&days=" + std::to_string(days); return request("GET", apiPath, &response); } // GET /api/recorded int getRecorded(nlohmann::json& response) { constexpr char apiPath[] = "recorded?limit=65535"; return request("GET", apiPath, &response); } // GET /api/reserves int getReserves(nlohmann::json& response) { constexpr char apiPath[] = "reserves?limit=65535"; return request("GET", apiPath, &response); } // GET /api/reserves/skips int getReservesSkips(nlohmann::json& response) { constexpr char apiPath[] = "reserves/skips?limit=65535"; return request("GET", apiPath, &response); } // GET /api/reserves/conflicts int getReservesConflicts(nlohmann::json& response) { constexpr char apiPath[] = "reserves/conflicts?limit=65535"; return request("GET", apiPath, &response); } // DELETE /api/recorded/:id int deleteRecordedProgram(const std::string id) { const auto apiPath = "recorded/" + id; return request("DELETE", apiPath); } // DELETE /api/reserves/:id int deleteReserves(const std::string id) { const auto apiPath = "reserves/" + id; return request("DELETE", apiPath); } // DELETE /api/reserves/:id/skip int deleteReservesSkip(const std::string id) { const auto apiPath = "reserves/" + id + "/skip"; return request("DELETE", apiPath); } // POST /api/reserves int postReserves(const std::string id) { nlohmann::json body = { { "programId", std::stoull(id) }, { "allowEndLack", true }, }; constexpr char apiPath[] = "reserves"; return request("POST", apiPath, nullptr, body); } // GET /api/rules int getRules(nlohmann::json& response) { constexpr char apiPath[] = "rules?limit=65535"; return request("GET", apiPath, &response); } nlohmann::json createRulePayload(bool enabled, const std::string searchText, bool fullText, uint64_t channelId, unsigned int weekdays, unsigned int startHour, unsigned int endHour, bool anytime, const std::string directory) { uint16_t newWeekdays = weekdays ^ PVR_WEEKDAY_SUNDAY; newWeekdays <<= 1; if (weekdays & PVR_WEEKDAY_SUNDAY) { newWeekdays |= 0x01; } nlohmann::json body = { { "search", { { "keyword", searchText }, { "title", true }, { "description", fullText }, { "week", newWeekdays }, } }, { "option", { { "enable", enabled }, { "allowEndLack", true }, } } }; if (channelId == 0) { body["search"]["GR"] = true; body["search"]["BS"] = true; body["search"]["CS"] = true; body["search"]["SKY"] = true; } else { body["search"]["station"] = channelId; } if (!anytime) { body["search"]["startTime"] = startHour; body["search"]["timeRange"] = (24 + endHour - startHour) % 24; } if (!directory.empty()) { body["option"]["directory"] = directory; } return body; } // POST /api/rules int postRules(bool enabled, const std::string searchText, bool fullText, uint64_t channelId, unsigned int weekdays, unsigned int startHour, unsigned int endHour, bool anytime, const std::string directory) { constexpr char apiPath[] = "rules"; nlohmann::json body = createRulePayload(enabled, searchText, fullText, channelId, weekdays, startHour, endHour, anytime, directory); return request("POST", apiPath, nullptr, body); } // PUT /api/rules/:id int putRule(int id, bool enabled, const std::string searchText, bool fullText, uint64_t channelId, unsigned int weekdays, unsigned int startHour, unsigned int endHour, bool anytime, const std::string directory) { const auto apiPath = "rules/" + std::to_string(id); nlohmann::json body = createRulePayload(enabled, searchText, fullText, channelId, weekdays, startHour, endHour, anytime, directory); return request("PUT", apiPath, nullptr, body); } // PUT /api/rules/:id/:action int putRuleAction(int id, bool state) { const auto apiPath = "rules/" + std::to_string(id) + (state ? "/enable" : "/disable"); return request("PUT", apiPath); } // DELETE /api/rules/:id int deleteRule(int id) { const auto apiPath = "rules/" + std::to_string(id); return request("DELETE", apiPath); } // PUT /api/schedule/update int putScheduleUpdate() { constexpr char apiPath[] = "schedule/update"; return request("PUT", apiPath); } // GET /api/storage int getStorage(nlohmann::json& response) { constexpr char apiPath[] = "storage"; return request("GET", apiPath, &response); } // GET /api/docs int getDocs(nlohmann::json& response) { constexpr char apiPath[] = "docs"; return request("GET", apiPath, &response); } } // namespace api } // namespace epgstation
9,793
C++
.cpp
249
30.493976
227
0.580221
Harekaze/pvr.epgstation
33
6
2
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,784
storage.cpp
Harekaze_pvr_epgstation/src/epgstation/storage.cpp
/* * Copyright (C) 2015-2020 Yuki MIZUNO * https://github.com/Harekaze/pvr.epgstation/ * SPDX-License-Identifier: GPL-3.0-only */ #include "epgstation/storage.h" #include "epgstation/api.h" #include "epgstation/types.h" #include "kodi/libXBMC_addon.h" #include "json/json.hpp" extern ADDON::CHelper_libXBMC_addon* XBMC; namespace epgstation { PVR_ERROR Storage::getStorageInfo(long long* used, long long* total) { nlohmann::json response; if (api::getStorage(response) == api::REQUEST_FAILED) { return PVR_ERROR_SERVER_ERROR; } auto info = response.get<storage>(); *total = info.total / 1024; *used = info.used / 1024; return PVR_ERROR_NO_ERROR; } } // namespace epgstation
719
C++
.cpp
24
27.083333
68
0.717391
Harekaze/pvr.epgstation
33
6
2
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,785
docs.cpp
Harekaze_pvr_epgstation/src/epgstation/docs.cpp
/* * Copyright (C) 2015-2020 Yuki MIZUNO * https://github.com/Harekaze/pvr.epgstation/ * SPDX-License-Identifier: GPL-3.0-only */ #include "epgstation/docs.h" #include "epgstation/api.h" #include "kodi/libXBMC_addon.h" #include "json/json.hpp" #include <string> namespace epgstation { bool Docs::fetchSystemInfo() { nlohmann::json response; if (api::getDocs(response) == api::REQUEST_FAILED) { return false; } std::string name = response["info"]["title"].get<std::string>(); std::string version = response["info"]["version"].get<std::string>(); std::string hostname = response["host"].get<std::string>(); snprintf(Docs::backendName, sizeof(Docs::backendName), "%s", name.c_str()); snprintf(Docs::backendVersion, sizeof(Docs::backendVersion), "%s", version.c_str()); snprintf(Docs::backendHostname, sizeof(Docs::backendHostname), "%s", hostname.c_str()); return true; } const char* Docs::getBackendName() { if (std::char_traits<char>::length(Docs::backendName) == 0) { Docs::fetchSystemInfo(); } return Docs::backendName; } const char* Docs::getBackendVersion() { if (std::char_traits<char>::length(Docs::backendVersion) == 0) { Docs::fetchSystemInfo(); } return Docs::backendVersion; } const char* Docs::getBackendHostname() { if (std::char_traits<char>::length(Docs::backendHostname) == 0) { Docs::fetchSystemInfo(); } return Docs::backendHostname; } char Docs::backendName[128] = { 0 }; char Docs::backendVersion[128] = { 0 }; char Docs::backendHostname[128] = { 0 }; } // namespace epgstation
1,617
C++
.cpp
50
28.92
91
0.680359
Harekaze/pvr.epgstation
33
6
2
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,786
genre.h
Harekaze_pvr_epgstation/include/epgstation/genre.h
/* * Copyright (C) 2015-2020 Yuki MIZUNO * https://github.com/Harekaze/pvr.epgstation/ * SPDX-License-Identifier: GPL-3.0-only */ #ifndef EPGSTATION_GENRE_H #define EPGSTATION_GENRE_H #include "kodi/xbmc_epg_types.h" // ARIB STD-B10 v5 // https://www.etsi.org/deliver/etsi_en/300400_300499/300468/01.11.01_60/en_300468v011101p.pdf namespace epgstation { typedef struct genre_code { uint8_t main; uint8_t sub; } genre_code_t; static genre_code_t getGenreCodeFromContentNibble(uint8_t level1, uint8_t level2) { switch (level1) { case 0x00: { // ニュース/報道 switch (level2) { case 0x00: // 定時・総合 return { EPG_EVENT_CONTENTMASK_NEWSCURRENTAFFAIRS, 0x00 }; // News/Current Affairs (general) case 0x01: // 天気 return { EPG_EVENT_CONTENTMASK_NEWSCURRENTAFFAIRS, 0x01 }; // News/Weather report case 0x02: // 特集・ドキュメント case 0x03: // 政治・国会 return { EPG_EVENT_CONTENTMASK_NEWSCURRENTAFFAIRS, 0x03 }; // Documentary case 0x04: // 経済・市況 case 0x05: // 海外・国際 case 0x06: // 解説 return { EPG_EVENT_CONTENTMASK_NEWSCURRENTAFFAIRS, 0x02 }; // News magazine case 0x07: // 討論・会談 return { EPG_EVENT_CONTENTMASK_NEWSCURRENTAFFAIRS, 0x04 }; // Discussion/interview/debate case 0x08: // 報道特番 case 0x09: // ローカル・地域 case 0x0a: // 交通 default: return { EPG_EVENT_CONTENTMASK_NEWSCURRENTAFFAIRS, 0x00 }; } case 0x01: { // スポーツ switch (level2) { case 0x00: // スポーツニュース return { EPG_EVENT_CONTENTMASK_SPORTS, 0x02 }; // sports magazines case 0x01: // 野球 return { EPG_EVENT_CONTENTMASK_SPORTS, 0x05 }; // team sports (excluding football) case 0x02: // サッカー return { EPG_EVENT_CONTENTMASK_SPORTS, 0x03 }; // football/scooer case 0x03: // ゴルフ return { EPG_EVENT_CONTENTMASK_SPORTS, 0x00 }; // sports (general) case 0x04: // その他の球技 return { EPG_EVENT_CONTENTMASK_SPORTS, 0x00 }; // sports (general) case 0x05: // 相撲・格闘技 return { EPG_EVENT_CONTENTMASK_SPORTS, 0x0b }; // martial sports case 0x06: // オリンピック・国際大会 return { EPG_EVENT_CONTENTMASK_SPORTS, 0x01 }; // special events (Olympic Games, World Cup, etc.) case 0x07: // マラソン・陸上・水泳 return { EPG_EVENT_CONTENTMASK_SPORTS, 0x06 }; // athletics case 0x08: // モータースポーツ return { EPG_EVENT_CONTENTMASK_SPORTS, 0x07 }; // motor sport case 0x09: // マリン・ウィンタースポーツ return { EPG_EVENT_CONTENTMASK_SPORTS, 0x08 }; // water sport // return {EPG_EVENT_CONTENTMASK_SPORTS,0x09}; // winter sport case 0x0a: // 競馬・公営競技 return { EPG_EVENT_CONTENTMASK_SPORTS, 0x0a }; // equestrian default: return { EPG_EVENT_CONTENTMASK_SPORTS, 0x00 }; // sports (general) } } case 0x02: { // 情報/ワイドショー switch (level2) { case 0x00: // 芸能・ワイドショー return { EPG_EVENT_CONTENTMASK_ARTSCULTURE, 0x04 }; // popular culture/traditional arts case 0x01: // ファッション return { EPG_EVENT_CONTENTMASK_ARTSCULTURE, 0x0b }; // fashion case 0x02: // 暮らし・住まい return { EPG_EVENT_CONTENTMASK_ARTSCULTURE, 0x00 }; // arts/culture (without music, general) case 0x03: // 健康・医療 return { EPG_EVENT_CONTENTMASK_LEISUREHOBBIES, 0x04 }; // fitness and health case 0x04: // ショッピング・通販 return { EPG_EVENT_CONTENTMASK_LEISUREHOBBIES, 0x06 }; // advertisement/shopping case 0x05: // グルメ・料理 return { EPG_EVENT_CONTENTMASK_LEISUREHOBBIES, 0x05 }; // cooking case 0x06: // イベント case 0x07: // 番組紹介・お知らせ return { EPG_EVENT_CONTENTMASK_ARTSCULTURE, 0x08 }; // broadcasting/press default: return { EPG_EVENT_CONTENTMASK_ARTSCULTURE, 0x00 }; // arts/culture (without music, general) } } case 0x03: { // ドラマ switch (level2) { case 0x00: // 国内ドラマ case 0x01: // 海外ドラマ return { EPG_EVENT_CONTENTMASK_MOVIEDRAMA, 0x00 }; // movie/drama (general) case 0x02: // 時代劇 return { EPG_EVENT_CONTENTMASK_MOVIEDRAMA, 0x07 }; // serious/classical/religious/historical movie/drama default: return { EPG_EVENT_CONTENTMASK_MOVIEDRAMA, 0x00 }; // movie/drama (general) } } case 0x04: { // 音楽 switch (level2) { case 0x00: // 国内ロック・ポップス case 0x01: // 海外ロック・ポップス return { EPG_EVENT_CONTENTMASK_MUSICBALLETDANCE, 0x01 }; // rock/pop case 0x02: // クラシック・オペラ return { EPG_EVENT_CONTENTMASK_MUSICBALLETDANCE, 0x02 }; // serious music/classical music case 0x03: // ジャズ・フュージョン return { EPG_EVENT_CONTENTMASK_MUSICBALLETDANCE, 0x04 }; // jazz case 0x04: // 歌謡曲・演歌 return { EPG_EVENT_CONTENTMASK_MUSICBALLETDANCE, 0x03 }; // folk/traditional music case 0x05: // ライブ・コンサート return { EPG_EVENT_CONTENTMASK_MUSICBALLETDANCE, 0x05 }; // musical/opera case 0x06: // ランキング・リクエスト case 0x07: // カラオケ・のど自慢 return { EPG_EVENT_CONTENTMASK_MUSICBALLETDANCE, 0x00 }; // music/ballet/dance (general) case 0x08: // 民謡・邦楽 case 0x09: // 童謡・キッズ case 0x0a: // 民族音楽・ワールドミュージック return { EPG_EVENT_CONTENTMASK_MUSICBALLETDANCE, 0x03 }; // folk/traditional music default: return { EPG_EVENT_CONTENTMASK_MUSICBALLETDANCE, 0x00 }; // music/ballet/dance (general) } } case 0x05: { // バラエティ switch (level2) { case 0x00: // クイズ case 0x01: // ゲーム return { EPG_EVENT_CONTENTMASK_SHOW, 0x01 }; // game show/quiz/contest case 0x02: // トークバラエティ return { EPG_EVENT_CONTENTMASK_SHOW, 0x03 }; // talk show case 0x03: // お笑い・コメディ return { EPG_EVENT_CONTENTMASK_SHOW, 0x02 }; // variety show case 0x04: // 音楽バラエティ case 0x05: // 旅バラエティ case 0x06: // 料理バラエティ default: return { EPG_EVENT_CONTENTMASK_SHOW, 0x00 }; // show/game show (general) } } case 0x06: { // 映画 switch (level2) { case 0x00: // 洋画 case 0x01: // 邦画 case 0x02: // アニメ default: return { EPG_EVENT_CONTENTMASK_MOVIEDRAMA, 0x00 }; // movie/drama (general) } } case 0x07: { // アニメ/特撮 switch (level2) { case 0x00: // 国内アニメ case 0x01: // 海外アニメ case 0x02: // 特撮 default: return { EPG_EVENT_CONTENTMASK_CHILDRENYOUTH, 0x05 }; // cartoons/puppets } } case 0x08: { // ドキュメンタリー/教養 switch (level2) { case 0x00: // 社会・時事 return { EPG_EVENT_CONTENTMASK_EDUCATIONALSCIENCE, 0x05 }; // social/spiritual sciences case 0x01: // 歴史・紀行 return { EPG_EVENT_CONTENTMASK_EDUCATIONALSCIENCE, 0x04 }; // foreign countries/expeditions case 0x02: // 自然・動物・環境 return { EPG_EVENT_CONTENTMASK_EDUCATIONALSCIENCE, 0x01 }; // nature/animals/environment case 0x03: // 宇宙・科学・医学 return { EPG_EVENT_CONTENTMASK_EDUCATIONALSCIENCE, 0x03 }; // medicine/physiology/psychology case 0x04: // カルチャー・伝統文化 case 0x05: // 文学・文芸 case 0x06: // スポーツ case 0x07: // ドキュメンタリー全般 case 0x08: // インタビュー・討論 default: return { EPG_EVENT_CONTENTMASK_EDUCATIONALSCIENCE, 0x00 }; // education/science/factual topics (general) } } case 0x09: { // 劇場/公演 switch (level2) { case 0x00: // 現代劇・新劇 return { EPG_EVENT_CONTENTMASK_MUSICBALLETDANCE, 0x03 }; // folk/traditional music case 0x01: // ミュージカル return { EPG_EVENT_CONTENTMASK_MUSICBALLETDANCE, 0x05 }; // musical/opera case 0x02: // ダンス・バレエ return { EPG_EVENT_CONTENTMASK_MUSICBALLETDANCE, 0x06 }; // ballet case 0x03: // 落語・演芸 case 0x04: // 歌舞伎・古典 return { EPG_EVENT_CONTENTMASK_MUSICBALLETDANCE, 0x03 }; // folk/traditional music default: return { EPG_EVENT_CONTENTMASK_MUSICBALLETDANCE, 0x00 }; // music/ballet/dance (general) } } case 0x0a: { // 趣味/教育 switch (level2) { case 0x00: // 旅・釣り・アウトドア return { EPG_EVENT_CONTENTMASK_LEISUREHOBBIES, 0x01 }; // tourism/travel case 0x01: // 園芸・ペット・手芸 return { EPG_EVENT_CONTENTMASK_LEISUREHOBBIES, 0x07 }; // gardening // return {EPG_EVENT_CONTENTMASK_LEISUREHOBBIES,0x02}; // handicraft case 0x02: // 音楽・美術・工芸 case 0x03: // 囲碁・将棋 case 0x04: // 麻雀・パチンコ return { EPG_EVENT_CONTENTMASK_LEISUREHOBBIES, 0x00 }; // leisure hobbies (general) case 0x05: // 車・オートバイ return { EPG_EVENT_CONTENTMASK_LEISUREHOBBIES, 0x03 }; // motoring case 0x06: // コンピュータ・TVゲーム return { EPG_EVENT_CONTENTMASK_EDUCATIONALSCIENCE, 0x02 }; // technology/natural sciences case 0x07: // 会話・語学 return { EPG_EVENT_CONTENTMASK_EDUCATIONALSCIENCE, 0x07 }; // languages case 0x08: // 幼児・小学生 case 0x09: // 中学生・高校生 case 0x0a: // 大学生・受験 return { EPG_EVENT_CONTENTMASK_EDUCATIONALSCIENCE, 0x00 }; // education/science/factual topics (general) case 0x0b: // 生涯教育・資格 return { EPG_EVENT_CONTENTMASK_EDUCATIONALSCIENCE, 0x06 }; // further education case 0x0c: // 教育問題 default: return { EPG_EVENT_CONTENTMASK_EDUCATIONALSCIENCE, 0x00 }; // education/science/factual topics (general) } } case 0x0b: { // 福祉 switch (level2) { case 0x00: // 高齢者 case 0x01: // 障害者 case 0x02: // 社会福祉 case 0x03: // ボランティア case 0x04: // 手話 case 0x05: // 文字(字幕) case 0x06: // 音声解説 default: return { EPG_EVENT_CONTENTMASK_EDUCATIONALSCIENCE, 0x00 }; // education/science/factual topics (general) } } default: return { EPG_EVENT_CONTENTMASK_UNDEFINED, 0x00 }; } } } } // namespace epgstation #endif /* end of include guard */
11,491
C++
.h
240
33.645833
116
0.59976
Harekaze/pvr.epgstation
33
6
2
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,787
types.h
Harekaze_pvr_epgstation/include/epgstation/types.h
/* * Copyright (C) 2015-2020 Yuki MIZUNO * https://github.com/Harekaze/pvr.epgstation/ * SPDX-License-Identifier: GPL-3.0-only */ #ifndef EPGSTATION_TYPES_H #define EPGSTATION_TYPES_H #include "json/json.hpp" #include <string> #define OPTIONAL_JSON_FROM(v) \ if (nlohmann_json_j.contains(#v) && !nlohmann_json_j[#v].is_null()) { \ NLOHMANN_JSON_FROM(v); \ } namespace epgstation { class storage { public: long long total; long long used; NLOHMANN_DEFINE_TYPE_INTRUSIVE(storage, total, used); }; enum ReservedState { STATE_RESERVED, STATE_CONFLICT, STATE_SKIPPED, }; class program { public: uint64_t id; uint64_t programId; uint64_t channelId; uint64_t eventId; std::string channelType; std::string name; std::string description; std::string extended; time_t startAt; time_t endAt; uint8_t genre1 = 0xff; uint8_t genre2 = 0xff; bool recording; bool hasThumbnail; bool original; std::vector<std::pair<uint64_t, std::string>> encoded; int16_t ruleId = 0; // Optional for reserved program ReservedState state; // Optional for reserved program friend void from_json(const nlohmann::json& nlohmann_json_j, program& nlohmann_json_t) { NLOHMANN_JSON_FROM(id); OPTIONAL_JSON_FROM(programId); OPTIONAL_JSON_FROM(eventId); NLOHMANN_JSON_FROM(channelId); NLOHMANN_JSON_FROM(channelType); NLOHMANN_JSON_FROM(name); OPTIONAL_JSON_FROM(description); OPTIONAL_JSON_FROM(extended); nlohmann_json_t.startAt = static_cast<time_t>(nlohmann_json_j["startAt"].get<long long>() / 1000ll); nlohmann_json_t.endAt = static_cast<time_t>(nlohmann_json_j["endAt"].get<long long>() / 1000ll); OPTIONAL_JSON_FROM(genre1); OPTIONAL_JSON_FROM(genre2); OPTIONAL_JSON_FROM(recording); OPTIONAL_JSON_FROM(hasThumbnail); OPTIONAL_JSON_FROM(original); if (nlohmann_json_j.contains("encoded") && nlohmann_json_j["encoded"].is_array()) { std::transform(nlohmann_json_j["encoded"].begin(), nlohmann_json_j["encoded"].end(), std::back_inserter(nlohmann_json_t.encoded), [](const nlohmann::json& e) { return std::make_pair(e["encodedId"], e["name"]); }); } } }; class channel { public: uint64_t id; uint32_t serviceId; uint32_t networkId; std::string name; bool hasLogoData; std::string channelType; uint8_t channelTypeId; uint8_t type; uint8_t remoteControlKeyId; std::string channelStr; int internalId; // for internal use friend void from_json(const nlohmann::json& nlohmann_json_j, epgstation::channel& nlohmann_json_t) { NLOHMANN_JSON_FROM(id); NLOHMANN_JSON_FROM(serviceId); NLOHMANN_JSON_FROM(networkId); NLOHMANN_JSON_FROM(name); NLOHMANN_JSON_FROM(hasLogoData); NLOHMANN_JSON_FROM(channelType); OPTIONAL_JSON_FROM(channelTypeId); NLOHMANN_JSON_FROM(type); OPTIONAL_JSON_FROM(remoteControlKeyId); if (nlohmann_json_j.contains("channel") && nlohmann_json_j["channel"].is_string()) { nlohmann_json_t.channelStr = nlohmann_json_j["channel"]; } } }; class rule { public: uint32_t id; std::string keyword; bool title = true; bool description = false; bool enable = true; uint16_t week = 0; uint64_t station = 0; uint16_t startTime = 0; uint16_t timeRange = 0; std::string directory = ""; friend void from_json(const nlohmann::json& nlohmann_json_j, rule& nlohmann_json_t) { NLOHMANN_JSON_FROM(id); NLOHMANN_JSON_FROM(keyword); OPTIONAL_JSON_FROM(title); OPTIONAL_JSON_FROM(description); NLOHMANN_JSON_FROM(enable); NLOHMANN_JSON_FROM(week); nlohmann_json_t.week = ((nlohmann_json_t.week & 0b00000001) << 6) | ((nlohmann_json_t.week & 0b01111110) >> 1); OPTIONAL_JSON_FROM(station); OPTIONAL_JSON_FROM(startTime); OPTIONAL_JSON_FROM(timeRange); OPTIONAL_JSON_FROM(directory); } }; } // namespace epgstation #endif /* end of include guard */
4,299
C++
.h
127
28.031496
171
0.643269
Harekaze/pvr.epgstation
33
6
2
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,789
docs.h
Harekaze_pvr_epgstation/src/epgstation/docs.h
/* * Copyright (C) 2015-2020 Yuki MIZUNO * https://github.com/Harekaze/pvr.epgstation/ * SPDX-License-Identifier: GPL-3.0-only */ #ifndef SRC_EPGSTATION_DOCS_H_ #define SRC_EPGSTATION_DOCS_H_ #include <iostream> namespace epgstation { class Docs { private: static char backendName[128]; static char backendVersion[128]; static char backendHostname[128]; static bool fetchSystemInfo(); public: static const char* getBackendName(); static const char* getBackendVersion(); static const char* getBackendHostname(); }; } // namespace epgstation #endif // SRC_EPGSTATION_DOCS_H_
608
C++
.h
22
25.045455
46
0.749571
Harekaze/pvr.epgstation
33
6
2
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,790
storage.h
Harekaze_pvr_epgstation/src/epgstation/storage.h
/* * Copyright (C) 2015-2020 Yuki MIZUNO * https://github.com/Harekaze/pvr.epgstation/ * SPDX-License-Identifier: GPL-3.0-only */ #ifndef SRC_EPGSTATION_STORAGE_H_ #define SRC_EPGSTATION_STORAGE_H_ #include <iostream> #include "kodi/xbmc_pvr_types.h" namespace epgstation { class Storage { public: static PVR_ERROR getStorageInfo(long long* used, long long* total); }; } // namespace epgstation #endif // SRC_EPGSTATION_STORAGE_H_
442
C++
.h
16
25.9375
71
0.758865
Harekaze/pvr.epgstation
33
6
2
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,791
recorded.h
Harekaze_pvr_epgstation/src/epgstation/recorded.h
/* * Copyright (C) 2015-2020 Yuki MIZUNO * https://github.com/Harekaze/pvr.epgstation/ * SPDX-License-Identifier: GPL-3.0-only */ #ifndef SRC_EPGSTATION_RECORDED_H_ #define SRC_EPGSTATION_RECORDED_H_ #include "epgstation/types.h" #include <iostream> #include <string> #include <vector> namespace epgstation { class Recorded { public: std::string recordedStreamingPath; std::string recordedThumbnailPath; std::vector<program> programs; bool refresh(); bool remove(const std::string id); }; } // namespace epgstation #endif // SRC_EPGSTATION_RECORDED_H_
578
C++
.h
22
24.090909
46
0.754513
Harekaze/pvr.epgstation
33
6
2
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,792
rules.h
Harekaze_pvr_epgstation/src/epgstation/rules.h
/* * Copyright (C) 2015-2020 Yuki MIZUNO * https://github.com/Harekaze/pvr.epgstation/ * SPDX-License-Identifier: GPL-3.0-only */ #ifndef SRC_EPGSTATION_RULES_H_ #define SRC_EPGSTATION_RULES_H_ #include "epgstation/types.h" #include <iostream> #include <string> #include <vector> namespace epgstation { class Rule { public: std::vector<rule> rules; bool refresh(); bool add(bool enabled, const std::string searchText, bool fullText, uint64_t channelId, unsigned int weekdays, unsigned int startHour, unsigned int endHour, bool anytime, const std::string directory); bool edit(int id, bool enabled, const std::string searchText, bool fullText, uint64_t channelId, unsigned int weekdays, unsigned int startHour, unsigned int endHour, bool anytime, const std::string directory); bool enable(int id, bool enabled); bool remove(int id); }; } // namespace epgstation #endif // SRC_EPGSTATION_RULES_H_
926
C++
.h
23
37.913043
213
0.757778
Harekaze/pvr.epgstation
33
6
2
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,793
epgstation.h
Harekaze_pvr_epgstation/src/epgstation/epgstation.h
/* * Copyright (C) 2015-2020 Yuki MIZUNO * https://github.com/Harekaze/pvr.epgstation/ * SPDX-License-Identifier: GPL-3.0-only */ #ifndef SRC_EPGSTATION_EPGSTATION_H_ #define SRC_EPGSTATION_EPGSTATION_H_ #include "epgstation/channels.h" #include "epgstation/recorded.h" #include "epgstation/reserves.h" #include "epgstation/rules.h" #include "epgstation/schedule.h" #include "epgstation/storage.h" #endif // SRC_EPGSTATION_EPGSTATION_H_
443
C++
.h
14
30.214286
46
0.782201
Harekaze/pvr.epgstation
33
6
2
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,794
channels.h
Harekaze_pvr_epgstation/src/epgstation/channels.h
/* * Copyright (C) 2015-2020 Yuki MIZUNO * https://github.com/Harekaze/pvr.epgstation/ * SPDX-License-Identifier: GPL-3.0-only */ #ifndef SRC_EPGSTATION_CHANNELS_H_ #define SRC_EPGSTATION_CHANNELS_H_ #include "epgstation/types.h" #include <iostream> #include <map> #include <string> #include <vector> namespace epgstation { class Channels { public: std::string channelLogoPath; std::string liveStreamingPath; std::vector<epgstation::channel> channels; int getId(uint64_t realId); uint64_t getId(int internalId); bool refresh(); }; } // namespace epgstation #endif // SRC_EPGSTATION_CHANNELS_H_
624
C++
.h
24
23.75
46
0.749164
Harekaze/pvr.epgstation
33
6
2
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,795
schedule.h
Harekaze_pvr_epgstation/src/epgstation/schedule.h
/* * Copyright (C) 2015-2020 Yuki MIZUNO * https://github.com/Harekaze/pvr.epgstation/ * SPDX-License-Identifier: GPL-3.0-only */ #ifndef SRC_EPGSTATION_SCHEDULE_H_ #define SRC_EPGSTATION_SCHEDULE_H_ #include "epgstation/types.h" #include <iostream> #include <map> #include <string> #include <vector> namespace epgstation { class Schedule { public: std::map<uint32_t, std::vector<program>> list; std::vector<program> fetch(uint32_t channelId, time_t start, time_t end); bool update(); }; } // namespace epgstation #endif // SRC_EPGSTATION_SCHEDULE_H_
569
C++
.h
21
25.238095
77
0.741758
Harekaze/pvr.epgstation
33
6
2
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,796
api.h
Harekaze_pvr_epgstation/src/epgstation/api.h
/* * Copyright (C) 2015-2020 Yuki MIZUNO * https://github.com/Harekaze/pvr.epgstation/ * SPDX-License-Identifier: GPL-3.0-only */ #ifndef SRC_EPGSTATION_API_H_ #define SRC_EPGSTATION_API_H_ #include "json/json.hpp" #include <iostream> #include <string> namespace epgstation { namespace api { extern const int REQUEST_FAILED; extern std::string baseURL; // GET /api/channels int getChannels(nlohmann::json& response); // GET /api/schedule?type=:type int getScheduleAll(const std::string type, nlohmann::json& response); // GET /api/schedule/:id?time=:time&days=:days int getSchedule(const std::string id, const char* time, const uint16_t days, nlohmann::json& response); // GET /api/recorded int getRecorded(nlohmann::json& response); // GET /api/reserves int getReserves(nlohmann::json& response); // GET /api/reserves/skips int getReservesSkips(nlohmann::json& response); // GET /api/reserves/conflicts int getReservesConflicts(nlohmann::json& response); // DELETE /api/recorded/:id int deleteRecordedProgram(const std::string id); // DELETE /api/reserves/:id int deleteReserves(const std::string id); // DELETE /api/reserves/:id/skip int deleteReservesSkip(const std::string id); // POST /api/reserves int postReserves(const std::string id); // GET /api/rules int getRules(nlohmann::json& response); // POST /api/rules int postRules(bool enabled, const std::string searchText, bool fullText, uint64_t channelId, unsigned int weekdays, unsigned int startHour, unsigned int endHour, bool anytime, const std::string directory); // PUT /api/rules/:id int putRule(int id, bool enabled, const std::string searchText, bool fullText, uint64_t channelId, unsigned int weekdays, unsigned int startHour, unsigned int endHour, bool anytime, const std::string directory); // PUT /api/rules/:id/:action int putRuleAction(int id, bool state); // DELETE /api/rules/:id int deleteRule(int id); // PUT /api/scheduler int putScheduleUpdate(); // GET /api/storage int getStorage(nlohmann::json& response); // GET /api/docs int getDocs(nlohmann::json& response); } // namespace api } // namespace epgstation #endif // SRC_EPGSTATION_API_H_
2,308
C++
.h
55
37.563636
215
0.716143
Harekaze/pvr.epgstation
33
6
2
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,797
reserves.h
Harekaze_pvr_epgstation/src/epgstation/reserves.h
/* * Copyright (C) 2015-2020 Yuki MIZUNO * https://github.com/Harekaze/pvr.epgstation/ * SPDX-License-Identifier: GPL-3.0-only */ #ifndef SRC_EPGSTATION_RESERVES_H_ #define SRC_EPGSTATION_RESERVES_H_ #include "epgstation/types.h" #include <iostream> #include <string> #include <vector> namespace epgstation { class Reserve { public: std::vector<program> reserves; bool refresh(); bool add(const std::string id); bool remove(const std::string id); bool restore(const std::string id); }; } // namespace epgstation #endif // SRC_EPGSTATION_RESERVES_H_
575
C++
.h
22
23.954545
46
0.738657
Harekaze/pvr.epgstation
33
6
2
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,798
log.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/log.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2020 Vladimir Makeev. * * This program 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. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ #include "log.h" #include "settings.h" #include "utils.h" #include <chrono> #include <ctime> #include <fstream> #include <iomanip> #include <thread> namespace hooks { static void logAction(const std::string& logFile, const std::string& message) { using namespace std::chrono; const auto path{hooks::gameFolder() / logFile}; std::ofstream file(path.c_str(), std::ios_base::app); const std::time_t time{std::time(nullptr)}; const std::tm tm = *std::localtime(&time); const auto tid = std::this_thread::get_id(); file << "[" << std::put_time(&tm, "%c") << "]\t" << tid << "\t" << message << "\n"; } void logDebug(const std::string& logFile, const std::string& message) { if (userSettings().debugMode) { logAction(logFile, message); } } void logError(const std::string& logFile, const std::string& message) { logAction(logFile, message); } } // namespace hooks
1,726
C++
.cpp
48
33.416667
87
0.712403
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,799
image2memory.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/image2memory.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2023 Vladimir Makeev. * * This program 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. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ #include "image2memory.h" #include "mempool.h" #include "surfacedecompressdata.h" namespace hooks { // CMqImage2Surface16::IMqImage2 original destructor, it will properly destroy CImage2Memory objects static game::IMqImage2Vftable::Destructor image2SurfaceDtor = nullptr; // Custom vftable for CImage2Memory::IMqImage2 static game::IMqImage2Vftable image2MemoryImage2Vftable{}; // Custom vftable for CImage2Memory::IMqTexture static game::IMqTextureVftable image2MemoryTextureVftable{}; static void __fastcall img2MemoryDtor(CImage2Memory* thisptr, int /* %edx */, char flags) { thisptr->pixels.~vector(); if (image2SurfaceDtor) { image2SurfaceDtor(thisptr, flags); } } static CImage2Memory* textureToImage(game::IMqTexture* thisptr) { using namespace game; const std::intptr_t offset = offsetof(CImage2Memory, IMqTexture::vftable); const auto rawPtr = reinterpret_cast<std::uintptr_t>(thisptr) - offset; CImage2Memory* img2Mem = reinterpret_cast<CImage2Memory*>(rawPtr); return img2Mem; } static void __stdcall img2MemoryDraw(game::IMqTexture* thisptr, game::SurfaceDecompressData* decompressData) { using namespace game; CImage2Memory* img2Mem = textureToImage(thisptr); // Do actual drawing onto decompressData memory if (decompressData->noPalette) { const int height = img2Mem->size.y; const int width = img2Mem->size.x; const int pitch = decompressData->pitch * 2; char* dst = reinterpret_cast<char*>(decompressData->surfaceMemory); for (int i = 0; i < height; ++i, dst += pitch) { std::memcpy(dst, &img2Mem->pixels[i * width], width * sizeof(Color)); } } img2Mem->dirty = false; } CImage2Memory::CImage2Memory(std::uint32_t width, std::uint32_t height) : pixels(width * height, game::Color(255, 0, 255, 255)) { game::CMqImage2Surface16Api::get().constructor(this, width, height, 1, 0xff); } CImage2Memory* createImage2Memory(std::uint32_t width, std::uint32_t height) { using namespace game; CImage2Memory* img2Memory = (CImage2Memory*)Memory::get().allocate(sizeof(CImage2Memory)); new (img2Memory) CImage2Memory(width, height); static bool firstTime = true; if (firstTime) { firstTime = false; // Reuse CMqImage2Surface16::IMqImage2 vftable std::memcpy(&image2MemoryImage2Vftable, img2Memory->IMqImage2::vftable, sizeof(IMqImage2Vftable)); // Use Destructor and IsDirty methods from CMqImage2Surface16::IMqTexture vftable std::memcpy(&image2MemoryTextureVftable, img2Memory->IMqTexture::vftable, sizeof(IMqTextureVftable)); // Use custom draw method image2MemoryTextureVftable.draw = img2MemoryDraw; // Save original destructor for proper base class destrution image2SurfaceDtor = image2MemoryImage2Vftable.destructor; // Use custom destructor image2MemoryImage2Vftable.destructor = (IMqImage2Vftable::Destructor)img2MemoryDtor; } // Switch to our vftables img2Memory->IMqImage2::vftable = &image2MemoryImage2Vftable; img2Memory->IMqTexture::vftable = &image2MemoryTextureVftable; return img2Memory; } } // namespace hooks
4,105
C++
.cpp
92
39.5
100
0.729689
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,800
umunithooks.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/umunithooks.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Stanislav Egorov. * * This program 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. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ #include "umunithooks.h" #include "dbtable.h" #include "game.h" #include "mempool.h" #include "ummodifier.h" #include "umunit.h" #include "utils.h" namespace hooks { struct CUmUnitDataPatched : game::CUmUnitData { int regenerationStacked; }; game::CUmUnit* __fastcall umUnitCtorHooked(game::CUmUnit* thisptr, int /*%edx*/, const game::CMidgardID* modifierId, game::CDBTable* dbTable, const game::GlobalData** globalData) { using namespace game; const auto& umUnitApi = CUmUnitApi::get(); const auto& umUnitVftable = CUmUnitApi::vftable(); const auto& dbApi = CDBTableApi::get(); thisptr->usUnit.id = emptyId; CUmModifierApi::get().constructor(&thisptr->umModifier, modifierId, globalData); thisptr->data = (CUmUnitDataPatched*)Memory::get().allocate(sizeof(CUmUnitDataPatched)); if (thisptr->data) umUnitApi.dataConstructor(thisptr->data); thisptr->usUnit.vftable = umUnitVftable.usUnit; thisptr->usSoldier.vftable = umUnitVftable.usSoldier; thisptr->umModifier.vftable = umUnitVftable.umModifier; if (dbApi.eof(dbTable)) dbApi.missingValueException(dbApi.getName(dbTable), idToString(modifierId).c_str()); for (; !dbApi.eof(dbTable); dbApi.next(dbTable)) umUnitApi.readData(dbTable, thisptr->data, globalData); return thisptr; } game::CUmUnit* __fastcall umUnitCopyCtorHooked(game::CUmUnit* thisptr, int /*%edx*/, const game::CUmUnit* src) { using namespace game; const auto& umUnitVftable = CUmUnitApi::vftable(); thisptr->usUnit.id = src->usUnit.id; CUmModifierApi::get().copyConstructor(&thisptr->umModifier, &src->umModifier); thisptr->data = (CUmUnitDataPatched*)Memory::get().allocate(sizeof(CUmUnitDataPatched)); if (thisptr->data) CUmUnitApi::get().dataCopyConstructor(thisptr->data, src->data); thisptr->usUnit.vftable = umUnitVftable.usUnit; thisptr->usSoldier.vftable = umUnitVftable.usSoldier; thisptr->umModifier.vftable = umUnitVftable.umModifier; return thisptr; } int* __fastcall umUnitGetRegenHooked(const game::IUsSoldier* thisptr, int /*%edx*/) { using namespace game; const auto& fn = gameFunctions(); auto umunit = castSoldierToUmUnit(thisptr); auto data = (CUmUnitDataPatched*)umunit->data; auto unitImpl = umunit->umModifier.data->prev; auto soldier = fn.castUnitImplToSoldier(unitImpl); int stacked = *soldier->vftable->getRegen(soldier); stacked += data->regeneration.value; if (stacked > 100) stacked = 100; // The value can be potentially accessed by parallel thread, store only final result here data->regenerationStacked = stacked; return &data->regenerationStacked; } } // namespace hooks
3,813
C++
.cpp
87
37.114943
93
0.687838
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,801
imageptrvector.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/imageptrvector.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Stanislav Egorov. * * This program 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. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ #include "imageptrvector.h" #include "version.h" #include <array> namespace game::ImagePtrVectorApi { // clang-format off static std::array<Api, 4> functions = { { // Akella Api{ (Api::Destructor)0x495373, (Api::Reserve)0x4957e2, (Api::PushBack)0x4a4fd1, }, // Russobit Api{ (Api::Destructor)0x495373, (Api::Reserve)0x4957e2, (Api::PushBack)0x4a4fd1, }, // Gog Api{ (Api::Destructor)0x494df0, (Api::Reserve)0x495293, (Api::PushBack)0x4a4852, }, // Scenario Editor Api{ (Api::Destructor)0x4c871d, (Api::Reserve)0x4c8a7f, (Api::PushBack)0x4c8a01, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::ImagePtrVectorApi
1,649
C++
.cpp
55
25.890909
72
0.687854
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,802
cmdbattleresultmsg.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/cmdbattleresultmsg.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Stanislav Egorov. * * This program 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. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ #include "cmdbattleresultmsg.h" #include "version.h" #include <array> namespace game::CCmdBattleResultMsgApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::Destructor)0x415d7e, }, // Russobit Api{ (Api::Destructor)0x415d7e, }, // Gog Api{ (Api::Destructor)0x415a64, }, // Scenario Editor Api{ (Api::Destructor)nullptr, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } // clang-format off static std::array<CCommandMsgVftable*, 4> vftables = {{ // Akella (CCommandMsgVftable*)0x6d49f4, // Russobit (CCommandMsgVftable*)0x6d49f4, // Gog (CCommandMsgVftable*)0x6d2994, // Scenario Editor (CCommandMsgVftable*)nullptr, }}; // clang-format on CCommandMsgVftable* vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CCmdBattleResultMsgApi
1,800
C++
.cpp
63
25.285714
72
0.709827
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,803
sitecategories.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/sitecategories.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2024 Vladimir Makeev. * * This program 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. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ #include "sitecategories.h" #include "version.h" #include <array> namespace game { namespace SiteCategories { // clang-format off static std::array<Categories, 4> categories = {{ // Akella Categories{ (LSiteCategory*)0x83a290, (LSiteCategory*)0x83a2a8, (LSiteCategory*)0x83a270, (LSiteCategory*)0x83a280, }, // Russobit Categories{ (LSiteCategory*)0x83a290, (LSiteCategory*)0x83a2a8, (LSiteCategory*)0x83a270, (LSiteCategory*)0x83a280, }, // Gog Categories{ (LSiteCategory*)0x838240, (LSiteCategory*)0x838258, (LSiteCategory*)0x838220, (LSiteCategory*)0x838230, }, // Scenario Editor Categories{ (LSiteCategory*)0x6651a8, (LSiteCategory*)0x6651c0, (LSiteCategory*)0x665188, (LSiteCategory*)0x665198, } }}; static std::array<const void*, 4> vftables = {{ // Akella (const void*)0x6e88d4, // Russobit (const void*)0x6e88d4, // Gog (const void*)0x6e6874, // Scenario Editor (const void*)0x5cb054, }}; // clang-format on Categories& get() { return categories[static_cast<int>(hooks::gameVersion())]; } const void* vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace SiteCategories namespace LSiteCategoryTableApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::Constructor)0x594f45, (Api::Init)0x5950ac, (Api::ReadCategory)0x595124, (Api::InitDone)0x595067, (Api::FindCategoryById)nullptr, }, // Russobit Api{ (Api::Constructor)0x594f45, (Api::Init)0x5950ac, (Api::ReadCategory)0x595124, (Api::InitDone)0x595067, (Api::FindCategoryById)nullptr, }, // Gog Api{ (Api::Constructor)0x594035, (Api::Init)0x59419c, (Api::ReadCategory)0x594214, (Api::InitDone)0x594157, (Api::FindCategoryById)nullptr, }, // Scenario Editor Api{ (Api::Constructor)0x52F2CA, (Api::Init)0x52F431, (Api::ReadCategory)0x52F4A9, (Api::InitDone)0x52F3EC, (Api::FindCategoryById)nullptr, } }}; static std::array<const void*, 4> vftables = {{ // Akella (const void*)0x6eb6d4, // Russobit (const void*)0x6eb6d4, // Gog (const void*)0x6e9674, // Scenario Editor (const void*)0x5de02c, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } const void* vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace LSiteCategoryTableApi } // namespace game
3,544
C++
.cpp
131
22.267176
72
0.664803
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,804
modifgrouphooks.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/modifgrouphooks.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Stanislav Egorov. * * This program 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. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ #include "modifgrouphooks.h" #include "custommodifiers.h" #include "dbfaccess.h" #include "log.h" #include "modifgroup.h" namespace hooks { static const char dbfFileName[] = "LModifS.dbf"; game::LModifGroupTable* __fastcall modifGroupTableCtorHooked(game::LModifGroupTable* thisptr, int /*%edx*/, const char* globalsFolderPath, void* codeBaseEnvProxy) { using namespace game; logDebug("mss32Proxy.log", "LModifGroupTable c-tor hook started"); const auto& tableApi = LModifGroupTableApi::get(); auto& groups = LModifGroupApi::categories(); const auto dbfFilePath{std::filesystem::path(globalsFolderPath) / dbfFileName}; bool customGroupExists = utils::dbValueExists(dbfFilePath, "TEXT", customModifGroupName); if (customGroupExists) logDebug("mss32Proxy.log", "Found custom modifier category"); thisptr->bgn = nullptr; thisptr->end = nullptr; thisptr->allocatedMemEnd = nullptr; thisptr->allocator = nullptr; thisptr->vftable = LModifGroupTableApi::vftable(); tableApi.init(thisptr, codeBaseEnvProxy, globalsFolderPath, dbfFileName); tableApi.readCategory(groups.attack, thisptr, "L_ATTACK", dbfFileName); tableApi.readCategory(groups.unit, thisptr, "L_UNIT", dbfFileName); tableApi.readCategory(groups.stack, thisptr, "L_STACK", dbfFileName); if (customGroupExists) tableApi.readCategory(&getCustomModifiers().group, thisptr, customModifGroupName, dbfFileName); tableApi.initDone(thisptr); logDebug("mss32Proxy.log", "LModifGroupTable c-tor hook finished"); return thisptr; } } // namespace hooks
2,629
C++
.cpp
55
40.690909
93
0.696178
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,805
popupdialoginterf.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/popupdialoginterf.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program 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. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ #include "popupdialoginterf.h" #include "version.h" #include <array> namespace game::CPopupDialogInterfApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::Constructor)0x5cad0b, }, // Russobit Api{ (Api::Constructor)0x5cad0b, }, // Gog Api{ (Api::Constructor)0x5c9c41, }, // Scenario Editor Api{ (Api::Constructor)0x4d2a34, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CPopupDialogInterfApi
1,402
C++
.cpp
47
26.574468
72
0.71037
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,806
deathanimcat.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/deathanimcat.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Stanislav Egorov. * * This program 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. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ #include "deathanimcat.h" #include "version.h" #include <array> namespace game::DeathAnimCategories { // clang-format off static std::array<Categories, 4> categories = {{ // Akella Categories{ (LDeathAnimCategory*)0x83a2b8, (LDeathAnimCategory*)0x83a2c8, (LDeathAnimCategory*)0x83a2d8, (LDeathAnimCategory*)0x83a2e8, (LDeathAnimCategory*)0x83a2f8, (LDeathAnimCategory*)0x83a308, (LDeathAnimCategory*)0x83a318, (LDeathAnimCategory*)0x83a330, }, // Russobit Categories{ (LDeathAnimCategory*)0x83a2b8, (LDeathAnimCategory*)0x83a2c8, (LDeathAnimCategory*)0x83a2d8, (LDeathAnimCategory*)0x83a2e8, (LDeathAnimCategory*)0x83a2f8, (LDeathAnimCategory*)0x83a308, (LDeathAnimCategory*)0x83a318, (LDeathAnimCategory*)0x83a330, }, // Gog Categories{ (LDeathAnimCategory*)0x838268, (LDeathAnimCategory*)0x838278, (LDeathAnimCategory*)0x838288, (LDeathAnimCategory*)0x838298, (LDeathAnimCategory*)0x8382a8, (LDeathAnimCategory*)0x8382b8, (LDeathAnimCategory*)0x8382c8, (LDeathAnimCategory*)0x8382e0, }, // Scenario Editor Categories{ (LDeathAnimCategory*)0x665c38, (LDeathAnimCategory*)0x665c48, (LDeathAnimCategory*)0x665c58, (LDeathAnimCategory*)0x665c68, (LDeathAnimCategory*)0x665c78, (LDeathAnimCategory*)0x665c88, (LDeathAnimCategory*)0x665c98, (LDeathAnimCategory*)0x665cb0, }, }}; // clang-format on Categories& get() { return categories[static_cast<int>(hooks::gameVersion())]; } } // namespace game::DeathAnimCategories
2,542
C++
.cpp
75
28.493333
72
0.706336
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,807
game.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/game.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2020 Vladimir Makeev. * * This program 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. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ #include "game.h" #include "version.h" #include <array> namespace game { // clang-format off static std::array<Functions, 4> functions = {{ // Akella Functions{ (RespopupInitFunc)0x4893ad, (ToggleShowBannersInitFunc)0x5b4015, (AddUnitToHireList)0x5d5bb4, (AddSideshowUnitToHireList)0x5d5ab6, (AddPlayerUnitsToHireList)0x5d59e8, (CreateBuildingType)0x58bf67, (AddObjectAndCheckDuplicates)0x59c0a8, (ChooseUnitLane)0x5d6abb, (GetLordByPlayer)0x5e6323, (IsTurnValid)0x5879f3, (GetAllyOrEnemyGroupId)0x65afb2, (FindUnitById)0x625180, (CastUnitImplToSoldier)0x40a79d, (CastUnitImplToStackLeader)0x40a7c3, (CreateBatAttack)0x64630e, (GetAttackById)0x645df6, (IsUnitImmuneToAttack)0x65baa8, (GetAttackClassWardFlagPosition)0x623e12, (AttackClassToString)0x5c7af0, (GetAttackSourceWardFlagPosition)0x622dfe, (GetStackFortRuinGroup)0x5f6304, (GetStackFortRuinGroupForChange)0x5f6349, (GetStackFortRuinForChange)0x5f6255, (GetStackFortRuinId)0x5eba8e, (GetStackIdByUnitId)0x5ebabe, (GetFortIdByUnitId)0x5ebbc8, (GetRuinIdByUnitId)0x5ebccb, (DeletePlayerBuildings)0x422498, (GetInterfaceText)0x5c8f38, (ComputePlayerDailyIncome)0x5db82a, (ComputeDamage)0x65ccc7, (ComputeDamageMax)0x61f05c, (ComputeDamageWithBuffs)0x5d3e80, (ComputeArmor)0x5d3d5e, (MarkMapPosition)0x5cdf6f, (GetUnitLevelByImplId)0x599581, (GetAttackPower)0x628b0a, (IsGroupOwnerPlayerHuman)0x628165, (AttackShouldMiss)0x626b5f, (GenerateRandomNumber)0x548e10, (GenerateRandomNumberStd)0x548e67, (GetUnitPositionInGroup)0x65fb1e, (GetSummonUnitImplIdByAttack)0x661fe0, (GetSummonUnitImplId)0x664b5c, (GetAttackImplMagic)0x647561, (GetUnitHealAttackNumber)0x6283fb, (GetAttackQtyDamageOrHeal)0x61efc4, (ComputeUnitEffectiveHpForAi)0x5d0053, (ApplyDynUpgradeToAttackData)0x59a76b, (ComputeUnitDynUpgrade)0x5998fc, (ShowMovementPath)0x4cd533, (GetMidgardPlan)0x5f756f, (CastUnitImplToNoble)0x41b8cc, (GetBlockingPathNearbyStackId)0x5ce204, (GetFortOrRuinEntrance)0x4cdb5a, (StackCanMoveToPosition)0x4cdae4, (IsWaterTileSurroundedByWater)0x5e773e, (GetStackPositionById)0x5eecf2, (ApplyPercentModifiers)0x577515, (GenerateAttackDescription)0x57652b, (CreateMenuAnimation)0x4eb465, (GetAttackSourceText)0x61e1df, (AppendAttackSourceText)0x61e923, (IsRaceCategoryUnplayable)0x5e6691, (ValidateRaces)0x582ecb, (CheckRaceExist)0x582f6f, (GetUnitAttackSourceImmunities)0x408b0d, (GetSoldierAttackSourceImmunities)0x61e3c8, (GetTerrainByAbbreviation)0x5a6fbb, (GetTerrainByRace)0x5f105e, (GetTerrainByRace)0x5e6449, (GetRaceByTerrain)0x5e64c4, (GetRaceByTerrain)0x5db0ab, (GetNumberByTerrainGround)0x5cbf2f, (ThrowGenericException)0x596690, (IgnorePlayerEvents)0x5e66ec, (GetRacePreviewImage)0x4f1c4c, (GetSoldierImmunityAiRating)0x5de4e6, (GetAttackClassAiRating)0x5de83f, (GetAttackReachAiRating)0x5dea5c, (GetUnitPositionDistance)0x65c053, (GetUnitRaceCategory)0x65472b, (IsGroupSuitableForAiNobleMisfit)0x45c8e5, (IsUnitSuitableForAiNobleDuel)0x45c9b3, (IsAttackEffectiveAgainstGroup)0x5d269c, (IsAttackBetterThanItemUsage)0x452aa9, (ComputeAttackDamageCheckAltAttack)0x5d400c, (FillAttackTransformIdList)0x5989b2, (IsSmallMeleeFighter)0x44c5de, (CAiHireUnitEval)0x44c89a, (GetMeleeUnitToHireAiRating)0x44cad9, (ComputeTargetUnitAiPriority)0x5d00c0, (IsPlayerRaceUnplayable)0x5e6643, (IsSupportAttackClass)0x631e50, (GetUnitAttacks)0x645fe5, (GetItemAttack)0x646182, (IsUnitUseAdditionalAnimation)0x5c4f1a, (CheckUnitForHire)0x4b53e6, (CheckUnitForHire)0x4b58d2, (CastUnitImplToRacialSoldier)0x4482f6, (BuildLordSpecificBuildings)0x422411, (AddCapitalBuilding)0x4224ec, (CastUnitImplToLeader)0x424a87, (GetBaseUnitImplId)0x64ae7f, (GetUnitImplDamageMax)0x61f0a7, (ReadGlobalAttacks)0x593d63, (GetAltAttackIdCheckClass)0x59a965, (UnitHasDoppelgangerAttack)0x62a88c, (GetDeathAnimationByUnitOrItemId)0x6492e3, (OemToCharA)0x6ce410, (ThrowScenarioException)0x60b3b9, (LoadScenarioMap)0x429dc6, (CreateUnitFaceImage)0x5b18e9, (CanApplyPotionToUnit)0x5df760, (GetUpgradeUnitImplCheckXp)0x5d9e09, (ChangeUnitXpCheckUpgrade)0x5d8704, (IsUnitTierMax)0x5da04a, (IsUnitLevelNotMax)0x5da1bc, (IsUnitUpgradePending)0x61fb9d, (GetUnitImplIdForIsoUnitImage)0x684101, (GetUnitRequiredBuildings)0x61f7fe, (ComputeMovementCost)0x603bc6, (GetBuildingStatus)0x5ddcb3, }, // Russobit Functions{ (RespopupInitFunc)0x4893ad, (ToggleShowBannersInitFunc)0x5b4015, (AddUnitToHireList)0x5d5bb4, (AddSideshowUnitToHireList)0x5d5ab6, (AddPlayerUnitsToHireList)0x5d59e8, (CreateBuildingType)0x58bf67, (AddObjectAndCheckDuplicates)0x59c0a8, (ChooseUnitLane)0x5d6abb, (GetLordByPlayer)0x5e6323, (IsTurnValid)0x5879f3, (GetAllyOrEnemyGroupId)0x65afb2, (FindUnitById)0x625180, (CastUnitImplToSoldier)0x40a79d, (CastUnitImplToStackLeader)0x40a7c3, (CreateBatAttack)0x64630e, (GetAttackById)0x645df6, (IsUnitImmuneToAttack)0x65baa8, (GetAttackClassWardFlagPosition)0x623e12, (AttackClassToString)0x5c7af0, (GetAttackSourceWardFlagPosition)0x622dfe, (GetStackFortRuinGroup)0x5f6304, (GetStackFortRuinGroupForChange)0x5f6349, (GetStackFortRuinForChange)0x5f6255, (GetStackFortRuinId)0x5eba8e, (GetStackIdByUnitId)0x5ebabe, (GetFortIdByUnitId)0x5ebbc8, (GetRuinIdByUnitId)0x5ebccb, (DeletePlayerBuildings)0x422498, (GetInterfaceText)0x5c8f38, (ComputePlayerDailyIncome)0x5db82a, (ComputeDamage)0x65ccc7, (ComputeDamageMax)0x61f05c, (ComputeDamageWithBuffs)0x5d3e80, (ComputeArmor)0x5d3d5e, (MarkMapPosition)0x5cdf6f, (GetUnitLevelByImplId)0x599581, (GetAttackPower)0x628b0a, (IsGroupOwnerPlayerHuman)0x628165, (AttackShouldMiss)0x626b5f, (GenerateRandomNumber)0x548e10, (GenerateRandomNumberStd)0x548e67, (GetUnitPositionInGroup)0x65fb1e, (GetSummonUnitImplIdByAttack)0x661fe0, (GetSummonUnitImplId)0x664b5c, (GetAttackImplMagic)0x647561, (GetUnitHealAttackNumber)0x6283fb, (GetAttackQtyDamageOrHeal)0x61efc4, (ComputeUnitEffectiveHpForAi)0x5d0053, (ApplyDynUpgradeToAttackData)0x59a76b, (ComputeUnitDynUpgrade)0x5998fc, (ShowMovementPath)0x4cd533, (GetMidgardPlan)0x5f756f, (CastUnitImplToNoble)0x41b8cc, (GetBlockingPathNearbyStackId)0x5ce204, (GetFortOrRuinEntrance)0x4cdb5a, (StackCanMoveToPosition)0x4cdae4, (IsWaterTileSurroundedByWater)0x5e773e, (GetStackPositionById)0x5eecf2, (ApplyPercentModifiers)0x577515, (GenerateAttackDescription)0x57652b, (CreateMenuAnimation)0x4eb465, (GetAttackSourceText)0x61e1df, (AppendAttackSourceText)0x61e923, (IsRaceCategoryUnplayable)0x5e6691, (ValidateRaces)0x582ecb, (CheckRaceExist)0x582f6f, (GetUnitAttackSourceImmunities)0x408b0d, (GetSoldierAttackSourceImmunities)0x61e3c8, (GetTerrainByAbbreviation)0x5a6fbb, (GetTerrainByRace)0x5f105e, (GetTerrainByRace)0x5e6449, (GetRaceByTerrain)0x5e64c4, (GetRaceByTerrain)0x5db0ab, (GetNumberByTerrainGround)0x5cbf2f, (ThrowGenericException)0x596690, (IgnorePlayerEvents)0x5e66ec, (GetRacePreviewImage)0x4f1c4c, (GetSoldierImmunityAiRating)0x5de4e6, (GetAttackClassAiRating)0x5de83f, (GetAttackReachAiRating)0x5dea5c, (GetUnitPositionDistance)0x65c053, (GetUnitRaceCategory)0x65472b, (IsGroupSuitableForAiNobleMisfit)0x45c8e5, (IsUnitSuitableForAiNobleDuel)0x45c9b3, (IsAttackEffectiveAgainstGroup)0x5d269c, (IsAttackBetterThanItemUsage)0x452aa9, (ComputeAttackDamageCheckAltAttack)0x5d400c, (FillAttackTransformIdList)0x5989b2, (IsSmallMeleeFighter)0x44c5de, (CAiHireUnitEval)0x44c89a, (GetMeleeUnitToHireAiRating)0x44cad9, (ComputeTargetUnitAiPriority)0x5d00c0, (IsPlayerRaceUnplayable)0x5e6643, (IsSupportAttackClass)0x631e50, (GetUnitAttacks)0x645fe5, (GetItemAttack)0x646182, (IsUnitUseAdditionalAnimation)0x5c4f1a, (CheckUnitForHire)0x4b53e6, (CheckUnitForHire)0x4b58d2, (CastUnitImplToRacialSoldier)0x4482f6, (BuildLordSpecificBuildings)0x422411, (AddCapitalBuilding)0x4224ec, (CastUnitImplToLeader)0x424a87, (GetBaseUnitImplId)0x64ae7f, (GetUnitImplDamageMax)0x61f0a7, (ReadGlobalAttacks)0x593d63, (GetAltAttackIdCheckClass)0x59a965, (UnitHasDoppelgangerAttack)0x62a88c, (GetDeathAnimationByUnitOrItemId)0x6492e3, (OemToCharA)0x6ce410, (ThrowScenarioException)0x60b3b9, (LoadScenarioMap)0x429dc6, (CreateUnitFaceImage)0x5b18e9, (CanApplyPotionToUnit)0x5df760, (GetUpgradeUnitImplCheckXp)0x5d9e09, (ChangeUnitXpCheckUpgrade)0x5d8704, (IsUnitTierMax)0x5da04a, (IsUnitLevelNotMax)0x5da1bc, (IsUnitUpgradePending)0x61fb9d, (GetUnitImplIdForIsoUnitImage)0x684101, (GetUnitRequiredBuildings)0x61f7fe, (ComputeMovementCost)0x603bc6, (GetBuildingStatus)0x5ddcb3, }, // Gog Functions{ (RespopupInitFunc)0x488f96, (ToggleShowBannersInitFunc)0x5b32db, (AddUnitToHireList)0x5d4add, (AddSideshowUnitToHireList)0x5d49df, (AddPlayerUnitsToHireList)0x5d4911, (CreateBuildingType)0x58b0c2, (AddObjectAndCheckDuplicates)0x59b275, (ChooseUnitLane)0x5d59e4, (GetLordByPlayer)0x5e5038, (IsTurnValid)0x586ba8, (GetAllyOrEnemyGroupId)0x659a32, (FindUnitById)0x623cc0, (CastUnitImplToSoldier)0x40a3f9, (CastUnitImplToStackLeader)0x40a41f, (CreateBatAttack)0x644b3e, (GetAttackById)0x644626, (IsUnitImmuneToAttack)0x65a528, (GetAttackClassWardFlagPosition)0x6229a2, (AttackClassToString)0x5c6ad9, (GetAttackSourceWardFlagPosition)0x62198e, (GetStackFortRuinGroup)0x5f4f87, (GetStackFortRuinGroupForChange)0x5f4fcc, (GetStackFortRuinForChange)0x5f4ed8, (GetStackFortRuinId)0x5ea791, (GetStackIdByUnitId)0x5ea7c1, (GetFortIdByUnitId)0x5ea8cb, (GetRuinIdByUnitId)0x5ea9ce, (DeletePlayerBuildings)0x421fb6, (GetInterfaceText)0x5c7f06, (ComputePlayerDailyIncome)0x5da55f, (ComputeDamage)0x65b747, (ComputeDamageMax)0x61db98, (ComputeDamageWithBuffs)0x5d2db1, (ComputeArmor)0x5d2c8f, (MarkMapPosition)0x5cce8b, (GetUnitLevelByImplId)0x59870b, (GetAttackPower)0x62764a, (IsGroupOwnerPlayerHuman)0x626ca5, (AttackShouldMiss)0x62569f, (GenerateRandomNumber)0x54851f, (GenerateRandomNumberStd)0x548576, (GetUnitPositionInGroup)0x65e59e, (GetSummonUnitImplIdByAttack)0x660a60, (GetSummonUnitImplId)0x6635dc, (GetAttackImplMagic)0x645d91, (GetUnitHealAttackNumber)0x626f3b, (GetAttackQtyDamageOrHeal)0x61db00, (ComputeUnitEffectiveHpForAi)0x5cef84, (ApplyDynUpgradeToAttackData)0x5998f5, (ComputeUnitDynUpgrade)0x598a86, (ShowMovementPath)0x4ccc2c, (GetMidgardPlan)0x5f61f2, (CastUnitImplToNoble)0x41b399, (GetBlockingPathNearbyStackId)0x5cd11f, (GetFortOrRuinEntrance)0x4cd253, (StackCanMoveToPosition)0x4cd1dd, (IsWaterTileSurroundedByWater)0x5e6453, (GetStackPositionById)0x5ed9b2, (ApplyPercentModifiers)0x576b6a, (GenerateAttackDescription)0x575b80, (CreateMenuAnimation)0x4ea917, (GetAttackSourceText)0x61cd1b, (AppendAttackSourceText)0x61d45f, (IsRaceCategoryUnplayable)0x5e53a6, (ValidateRaces)0x582121, (CheckRaceExist)0x5821c5, (GetUnitAttackSourceImmunities)0x408790, (GetSoldierAttackSourceImmunities)0x61cf04, (GetTerrainByAbbreviation)0x5a621c, (GetTerrainByRace)0x5efd35, (GetTerrainByRace)0x5e515e, (GetRaceByTerrain)0x5e51d9, (GetRaceByTerrain)0x5d9de0, (GetNumberByTerrainGround)0x5cae4b, (ThrowGenericException)0x5957b5, (IgnorePlayerEvents)0x5e5401, (GetRacePreviewImage)0x4f1095, (GetSoldierImmunityAiRating)0x5dd21b, (GetAttackClassAiRating)0x5dd574, (GetAttackReachAiRating)0x5dd791, (GetUnitPositionDistance)0x65aad3, (GetUnitRaceCategory)0x652f1b, (IsGroupSuitableForAiNobleMisfit)0x45c1e5, (IsUnitSuitableForAiNobleDuel)0x45c2b3, (IsAttackEffectiveAgainstGroup)0x5d15cd, (IsAttackBetterThanItemUsage)0x452475, (ComputeAttackDamageCheckAltAttack)0x5d2f3d, (FillAttackTransformIdList)0x597b00, (IsSmallMeleeFighter)0x44bff2, (CAiHireUnitEval)0x44c2ae, (GetMeleeUnitToHireAiRating)0x44c4e7, (ComputeTargetUnitAiPriority)0x5ceff1, (IsPlayerRaceUnplayable)0x5e5358, (IsSupportAttackClass)0x630890, (GetUnitAttacks)0x644815, (GetItemAttack)0x6449b2, (IsUnitUseAdditionalAnimation)0x5c3f03, (CheckUnitForHire)0x4b4a7f, (CheckUnitForHire)0x4b4f6b, (CastUnitImplToRacialSoldier)0x447ee5, (BuildLordSpecificBuildings)0x421f2f, (AddCapitalBuilding)0x42200a, (CastUnitImplToLeader)0x424565, (GetBaseUnitImplId)0x6497bf, (GetUnitImplDamageMax)0x61dbe3, (ReadGlobalAttacks)0x592e47, (GetAltAttackIdCheckClass)0x599aef, (UnitHasDoppelgangerAttack)0x6293cc, (GetDeathAnimationByUnitOrItemId)0x647b63, (OemToCharA)0x6cc40c, (ThrowScenarioException)0x609e84, (LoadScenarioMap)0x4297e3, (CreateUnitFaceImage)0x5b0bdd, (CanApplyPotionToUnit)0x5de495, (GetUpgradeUnitImplCheckXp)0x5d8b17, (ChangeUnitXpCheckUpgrade)0x5d7412, (IsUnitTierMax)0x5d8d58, (IsUnitLevelNotMax)0x5d8eca, (IsUnitUpgradePending)0x61e6d9, (GetUnitImplIdForIsoUnitImage)0x682a8b, (GetUnitRequiredBuildings)0x61e33a, (ComputeMovementCost)0x6027f3, (GetBuildingStatus)0x5dc9e8, }, // Scenario Editor Functions{ (RespopupInitFunc)nullptr, (ToggleShowBannersInitFunc)nullptr, (AddUnitToHireList)nullptr, (AddSideshowUnitToHireList)nullptr, (AddPlayerUnitsToHireList)nullptr, (CreateBuildingType)0x538b2d, (AddObjectAndCheckDuplicates)0x53cd9c, (ChooseUnitLane)0x4d8148, (GetLordByPlayer)nullptr, (IsTurnValid)0x52d22e, (GetAllyOrEnemyGroupId)nullptr, (FindUnitById)0x526a00, (CastUnitImplToSoldier)0x4088f7, (CastUnitImplToStackLeader)0x40b6c8, (CreateBatAttack)nullptr, (GetAttackById)nullptr, (IsUnitImmuneToAttack)nullptr, (GetAttackClassWardFlagPosition)0x525282, (AttackClassToString)nullptr, (GetAttackSourceWardFlagPosition)0x52426e, (GetStackFortRuinGroup)nullptr, (GetStackFortRuinGroupForChange)0x4f0d8e, (GetStackFortRuinForChange)0x4f0c9a, (GetStackFortRuinId)0x4ee371, (GetStackIdByUnitId)0x4ee3a1, (GetFortIdByUnitId)0x4ee4ab, (GetRuinIdByUnitId)0x4ee5ae, (DeletePlayerBuildings)nullptr, (GetInterfaceText)0x4d0a02, (ComputePlayerDailyIncome)nullptr, (ComputeDamage)nullptr, (ComputeDamageMax)0x522a74, (ComputeDamageWithBuffs)nullptr, (ComputeArmor)nullptr, (MarkMapPosition)nullptr, (GetUnitLevelByImplId)0x54416b, (GetAttackPower)nullptr, (IsGroupOwnerPlayerHuman)nullptr, (AttackShouldMiss)nullptr, (GenerateRandomNumber)nullptr, (GenerateRandomNumberStd)nullptr, (GetUnitPositionInGroup)nullptr, (GetSummonUnitImplIdByAttack)nullptr, (GetSummonUnitImplId)nullptr, (GetAttackImplMagic)nullptr, (GetUnitHealAttackNumber)nullptr, (GetAttackQtyDamageOrHeal)0x5229dc, (ComputeUnitEffectiveHpForAi)nullptr, (ApplyDynUpgradeToAttackData)0x545355, (ComputeUnitDynUpgrade)0x5444e6, (ShowMovementPath)nullptr, (GetMidgardPlan)0x4e5752, (CastUnitImplToNoble)0x4296d0, (GetBlockingPathNearbyStackId)nullptr, (GetFortOrRuinEntrance)nullptr, (StackCanMoveToPosition)nullptr, (IsWaterTileSurroundedByWater)0x4e41cf, (GetStackPositionById)0x4f227f, (ApplyPercentModifiers)0x4c7fb1, (GenerateAttackDescription)0x4c6fc7, (CreateMenuAnimation)nullptr, (GetAttackSourceText)0x521bf7, (AppendAttackSourceText)0x52233b, (IsRaceCategoryUnplayable)0x4e1d1a, (ValidateRaces)0x528524, (CheckRaceExist)0x5285c8, (GetUnitAttackSourceImmunities)nullptr, (GetSoldierAttackSourceImmunities)0x521de0, (GetTerrainByAbbreviation)0x53a5e3, (GetTerrainByRace)0x4e1b7a, (GetTerrainByRace)0x4e8519, (GetRaceByTerrain)nullptr, (GetRaceByTerrain)nullptr, (GetNumberByTerrainGround)0x4d3cb3, (ThrowGenericException)0x536c62, (IgnorePlayerEvents)nullptr, (GetRacePreviewImage)nullptr, (GetSoldierImmunityAiRating)0x4d7666, (GetAttackClassAiRating)0x4d79bf, (GetAttackReachAiRating)0x4d7bdc, (GetUnitPositionDistance)nullptr, (GetUnitRaceCategory)nullptr, (IsGroupSuitableForAiNobleMisfit)nullptr, (IsUnitSuitableForAiNobleDuel)nullptr, (IsAttackEffectiveAgainstGroup)nullptr, (IsAttackBetterThanItemUsage)nullptr, (ComputeAttackDamageCheckAltAttack)nullptr, (FillAttackTransformIdList)nullptr, (IsSmallMeleeFighter)nullptr, (CAiHireUnitEval)nullptr, (GetMeleeUnitToHireAiRating)nullptr, (ComputeTargetUnitAiPriority)nullptr, (IsPlayerRaceUnplayable)0x4e1ccc, (IsSupportAttackClass)nullptr, (GetUnitAttacks)nullptr, (GetItemAttack)nullptr, (IsUnitUseAdditionalAnimation)0x564ae7, (CheckUnitForHire)nullptr, (CheckUnitForHire)nullptr, (CastUnitImplToRacialSoldier)0x4cfc0a, (BuildLordSpecificBuildings)nullptr, (AddCapitalBuilding)nullptr, (CastUnitImplToLeader)0x4453c3, (GetBaseUnitImplId)nullptr, (GetUnitImplDamageMax)0x522abf, (ReadGlobalAttacks)0x537e05, (GetAltAttackIdCheckClass)0x54554f, (UnitHasDoppelgangerAttack)nullptr, (GetDeathAnimationByUnitOrItemId)nullptr, (OemToCharA)0x5ca344, (ThrowScenarioException)0x506057, (LoadScenarioMap)nullptr, (CreateUnitFaceImage)0x558cd6, (CanApplyPotionToUnit)nullptr, (GetUpgradeUnitImplCheckXp)nullptr, (ChangeUnitXpCheckUpgrade)nullptr, (IsUnitTierMax)0x4d585b, (IsUnitLevelNotMax)0x4d59cd, (IsUnitUpgradePending)0x523370, (GetUnitImplIdForIsoUnitImage)0x59acea, (GetUnitRequiredBuildings)0x52314a, (ComputeMovementCost)nullptr, (GetBuildingStatus)0x4d8a11, }, }}; static std::array<Variables, 4> variables = {{ // Akella Variables{ (int*)0x837ac8, (unsigned char*)0x837acc }, // Russobit Variables{ (int*)0x837ac8, (unsigned char*)0x837acc }, // Gog Variables{ (int*)0x835a78, (unsigned char*)0x835a7c }, // Scenario Editor Variables{ nullptr, nullptr }, }}; // clang-format on Functions& gameFunctions() { return functions[static_cast<int>(hooks::gameVersion())]; } Variables& gameVariables() { return variables[static_cast<int>(hooks::gameVersion())]; } } // namespace game
21,773
C++
.cpp
561
30.452763
72
0.7195
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,808
autoptr.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/autoptr.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Stanislav Egorov. * * This program 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. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ #include "autoptr.h" #include "version.h" #include <array> namespace game::AutoPtrApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::Reset)0x642930, }, // Russobit Api{ (Api::Reset)0x642930, }, // Gog Api{ (Api::Reset)0x6418f0, }, // Scenario Editor Api{ (Api::Reset)nullptr, } }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::AutoPtrApi
1,345
C++
.cpp
47
25.361702
72
0.698376
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,809
untransformeffecthooks.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/untransformeffecthooks.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Stanislav Egorov. * * This program 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. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ #include "batattackuntransformeffect.h" #include "battleattackinfo.h" #include "battlemsgdata.h" #include "game.h" #include "midunit.h" #include "unitutils.h" #include "ussoldier.h" #include "usunit.h" #include "visitors.h" namespace hooks { void __fastcall untransformEffectAttackOnHitHooked(game::CBatAttackUntransformEffect* thisptr, int /*%edx*/, game::IMidgardObjectMap* objectMap, game::BattleMsgData* battleMsgData, game::CMidgardID* targetUnitId, game::BattleAttackInfo** attackInfo) { using namespace game; const auto& fn = gameFunctions(); const CMidUnit* targetUnit = fn.findUnitById(objectMap, targetUnitId); const CMidgardID targetUnitImplId{targetUnit->unitImpl->id}; const auto targetSoldier = fn.castUnitImplToSoldier(targetUnit->unitImpl); bool prevAttackTwice = targetSoldier && targetSoldier->vftable->getAttackTwice(targetSoldier); const auto& visitors = VisitorApi::get(); visitors.undoTransformUnit(targetUnitId, objectMap, 1); updateAttackCountAfterTransformation(battleMsgData, targetUnit, prevAttackTwice); BattleAttackUnitInfo info{}; info.unitId = *targetUnitId; info.unitImplId = targetUnitImplId; BattleAttackInfoApi::get().addUnitInfo(&(*attackInfo)->unitsInfo, &info); const auto& battle = BattleMsgDataApi::get(); battle.removeTransformStatuses(targetUnitId, battleMsgData); battle.setUnitHp(battleMsgData, targetUnitId, targetUnit->currentHp); } } // namespace hooks
2,544
C++
.cpp
53
40.433962
98
0.698669
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,810
fonts.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/fonts.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2023 Vladimir Makeev. * * This program 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. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ #include "fonts.h" #include "version.h" #include <array> namespace game { namespace FontListPtrPairApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::LoadFromFile)0x5cb3ad, (Api::IsLoaded)0x5298ce, (Api::DefaultCtor)0x5296db, (Api::Destructor)0x529802, (Api::CopyConstructor)0x529799, }, // Russobit Api{ (Api::LoadFromFile)0x5cb3ad, (Api::IsLoaded)0x5298ce, (Api::DefaultCtor)0x5296db, (Api::Destructor)0x529802, (Api::CopyConstructor)0x529799, }, // Gog Api{ (Api::LoadFromFile)0x5ca2c9, (Api::IsLoaded)0x528dd9, (Api::DefaultCtor)0x528be6, (Api::Destructor)0x528d0d, (Api::CopyConstructor)0x528ca4, }, // Scenario Editor Api{ (Api::LoadFromFile)0x59a822, (Api::IsLoaded)0x4c1165, (Api::DefaultCtor)0x4c0f72, (Api::Destructor)0x4c1099, (Api::CopyConstructor)0x4c1030, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace FontListPtrPairApi namespace FontCacheApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::LoadFontFiles)0x5cb123, (Api::DataConstructor)0x5cb44c, (Api::DataDestructor)0x5cb4d7, (Api::SmartPtrSetData)0x4ffda8, (FontCachePtr*)0x83a980, }, // Russobit Api{ (Api::LoadFontFiles)0x5cb123, (Api::DataConstructor)0x5cb44c, (Api::DataDestructor)0x5cb4d7, (Api::SmartPtrSetData)0x4ffda8, (FontCachePtr*)0x83a980, }, // Gog Api{ (Api::LoadFontFiles)0x5ca03f, (Api::DataConstructor)0x5ca368, (Api::DataDestructor)0x5ca3f3, (Api::SmartPtrSetData)0x4ff0aa, (FontCachePtr*)0x838928, }, // Scenario Editor Api{ (Api::LoadFontFiles)0x59a598, (Api::DataConstructor)0x59a8c1, (Api::DataDestructor)0x59a94c, (Api::SmartPtrSetData)0x51ea55, (FontCachePtr*)0x666b90, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace FontCacheApi } // namespace game
3,097
C++
.cpp
107
23.719626
72
0.667338
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,811
citystackinterfhooks.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/citystackinterfhooks.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2023 Stanislav Egorov. * * This program 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. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ #include "citystackinterfhooks.h" #include "citystackinterf.h" #include "middragdropinterfhooks.h" #include "originalfunctions.h" namespace hooks { void __fastcall cityStackInterfOnObjectChangedHooked(game::CCityStackInterf* thisptr, int /*%edx*/, game::IMidScenarioObject* obj) { getOriginalFunctions().cityStackInterfOnObjectChanged(thisptr, obj); midDragDropInterfResetCurrentSource(&thisptr->dragDropInterf); } } // namespace hooks
1,368
C++
.cpp
31
38.741935
85
0.721471
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,812
gameimages.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/gameimages.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program 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. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ #include "gameimages.h" #include "version.h" #include <array> namespace game::GameImagesApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::GetGameImages)0x5ae7bc, (Api::GetImage)0x5aedfb, (Api::CreateOrFreeGameImages)0x4080e4, (Api::GetImageNames)0x5c817c, (Api::GetRaceLogoImageName)0x5c649b, (Api::GetFlagImage)0x5c138e, (Api::GetObjectiveImage)0x5b3c04, (Api::GetRiotImage)0x5b9616, (Api::GetCityImageNames)0x5c8252, (Api::GetVillageImage)0x5b93e7, (Api::GetCityPreviewLargeImageNames)0x5c66b8, (Api::GetCityIconImageNames)0x5c7046, (Api::GetIconImageByName)0x5b37b3, (Api::GetUnitIcon)0x5b996b, }, // Russobit Api{ (Api::GetGameImages)0x5ae7bc, (Api::GetImage)0x5aedfb, (Api::CreateOrFreeGameImages)0x4080e4, (Api::GetImageNames)0x5c817c, (Api::GetRaceLogoImageName)0x5c649b, (Api::GetFlagImage)0x5c138e, (Api::GetObjectiveImage)0x5b3c04, (Api::GetRiotImage)0x5b9616, (Api::GetCityImageNames)0x5c8252, (Api::GetVillageImage)0x5b93e7, (Api::GetCityPreviewLargeImageNames)0x5c66b8, (Api::GetCityIconImageNames)0x5c7046, (Api::GetIconImageByName)0x5b37b3, (Api::GetUnitIcon)0x5b996b, }, // Gog Api{ (Api::GetGameImages)0x5ada44, (Api::GetImage)0x5ae0bf, (Api::CreateOrFreeGameImages)0x407d6f, (Api::GetImageNames)0x5c7165, (Api::GetRaceLogoImageName)0x5c5484, (Api::GetFlagImage)0x5c0328, (Api::GetObjectiveImage)0x5b2eca, (Api::GetRiotImage)0x5b85b1, (Api::GetCityImageNames)0x5c723b, (Api::GetVillageImage)0x5b8382, (Api::GetCityPreviewLargeImageNames)0x5c56a1, (Api::GetCityIconImageNames)0x5c602f, (Api::GetIconImageByName)0x5b2a79, (Api::GetUnitIcon)0x5b891e, }, // Scenario Editor Api{ (Api::GetGameImages)0x5581c3, (Api::GetImage)0x558806, (Api::CreateOrFreeGameImages)0x43724a, (Api::GetImageNames)0x566a05, (Api::GetRaceLogoImageName)nullptr, (Api::GetFlagImage)0x562de2, (Api::GetObjectiveImage)0x554c7a, (Api::GetRiotImage)0x55571e, (Api::GetCityImageNames)0x566adb, (Api::GetVillageImage)0x5554ef, (Api::GetCityPreviewLargeImageNames)nullptr, (Api::GetCityIconImageNames)nullptr, (Api::GetIconImageByName)0x55498d, (Api::GetUnitIcon)0x55a52a, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::GameImagesApi
3,544
C++
.cpp
99
29.525253
72
0.689826
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,813
netcustomsession.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/netcustomsession.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program 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. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ #include "netcustomsession.h" #include "d2string.h" #include "lobbyclient.h" #include "log.h" #include "mempool.h" #include "mqnetsystem.h" #include "netcustomplayerclient.h" #include "netcustomplayerserver.h" #include "netcustomservice.h" #include <atomic> #include <chrono> #include <fmt/format.h> #include <thread> namespace hooks { extern std::atomic_bool hostAddressSet; bool CNetCustomSession::setMaxPlayers(int maxPlayers) { if (maxPlayers < 1 || maxPlayers > 4) { return false; } // -1 because room already have moderator. const auto result{tryChangeRoomPublicSlots(maxPlayers - 1)}; if (result) { this->maxPlayers = maxPlayers; } return result; } void __fastcall netCustomSessionDtor(CNetCustomSession* thisptr, int /*%edx*/, char flags) { logDebug("lobby.log", "CNetCustomSession d-tor called"); thisptr->name.~basic_string(); thisptr->players.~vector(); if (flags & 1) { logDebug("lobby.log", "CNetCustomSession d-tor frees memory"); game::Memory::get().freeNonZero(thisptr); } } game::String* __fastcall netCustomSessionGetName(CNetCustomSession* thisptr, int /*%edx*/, game::String* sessionName) { logDebug("lobby.log", "CNetCustomSession getName called"); game::StringApi::get().initFromString(sessionName, thisptr->name.c_str()); return sessionName; } int __fastcall netCustomSessionGetClientsCount(CNetCustomSession* thisptr, int /*%edx*/) { logDebug("lobby.log", "CNetCustomSession getClientsCount called"); return (int)thisptr->players.size(); } int __fastcall netCustomSessionGetMaxClients(CNetCustomSession* thisptr, int /*%edx*/) { logDebug("lobby.log", fmt::format("CNetCustomSession getMaxClients called. Max clients: {:d}", thisptr->maxPlayers)); return thisptr->maxPlayers; } void __fastcall netCustomSessionGetPlayers(CNetCustomSession* thisptr, int /*%edx*/, game::List<game::IMqNetPlayerEnum*>* players) { logDebug("lobby.log", "CNetCustomSession getPlayers called"); } void __fastcall netCustomSessionCreateClient(CNetCustomSession* thisptr, int /*%edx*/, game::IMqNetPlayerClient** client, game::IMqNetSystem* netSystem, game::IMqNetReception* reception, const char* clientName) { logDebug("lobby.log", fmt::format("CNetCustomSession createClient '{:s}' called", clientName)); auto customClient = thisptr->players.front(); // Finalize player setup here when we know all the settings auto& player = customClient->player; player.name = clientName; player.netSystem = netSystem; player.netReception = reception; *client = customClient; } void __fastcall netCustomSessionCreateServer(CNetCustomSession* thisptr, int /*%edx*/, game::IMqNetPlayerServer** server, game::IMqNetSystem* netSystem, game::IMqNetReception* reception) { logDebug("lobby.log", "CNetCustomSession createServer called"); *server = nullptr; if (!thisptr->server) { logDebug("lobby.log", "Player server is null !!!"); return; } auto& serverPlayer = thisptr->server->player; serverPlayer.netSystem = netSystem; serverPlayer.netReception = reception; *server = thisptr->server; } static game::IMqNetSessionVftable netCustomSessionVftable{ (game::IMqNetSessionVftable::Destructor)netCustomSessionDtor, (game::IMqNetSessionVftable::GetName)netCustomSessionGetName, (game::IMqNetSessionVftable::GetClientsCount)netCustomSessionGetClientsCount, (game::IMqNetSessionVftable::GetMaxClients)netCustomSessionGetMaxClients, (game::IMqNetSessionVftable::GetPlayers)netCustomSessionGetPlayers, (game::IMqNetSessionVftable::CreateClient)netCustomSessionCreateClient, (game::IMqNetSessionVftable::CreateServer)netCustomSessionCreateServer, }; game::IMqNetSession* createCustomNetSession(CNetCustomService* service, const char* sessionName, bool host) { auto session = (CNetCustomSession*)game::Memory::get().allocate(sizeof(CNetCustomSession)); new (session) CNetCustomSession(service, sessionName, host); session->vftable = &netCustomSessionVftable; return session; } } // namespace hooks
5,658
C++
.cpp
132
34.340909
99
0.65988
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false